首页 > 解决方案 > 当图像代码在它们之间使用组合器或任何其他方式时,如何仅从第一个 div 元素应用 css?

问题描述

我有 4 个 div。固定位置的第一个标题和其他 3 个是简单的 div。申请margin-top:2%;CSS 仅适用于 div 部分 1。我使用通用兄弟选择器 (~)。通过将此标题部分用于 div 然后它适用于所有 div 即部分 1,2 和 3 也。由于 1 个图像代码位于标题和其他 div 部分之间,相邻兄弟选择器 (+) 也不起作用。

我想仅在 div 第 1 节上应用 margin-top。

注意:实际上问题是我正在做一个已完成 80% 的项目(将近 290 页)。因此,在每个页面上为第 1 节的 div 提及一个类并应用 margin-top CSS 是非常耗时的。这就是为什么我想要一个棘手的解决方案。

我在项目中尝试的以下代码中提到的项目中使用了外部 CSS。

.header {
  z-index: 200;
  top: 0;
  width: 100%;
  height: 70x;
  position: fixed;
  background-color: #fbfcfe;
}

.header ~ div {
  margin-top: 2%;
}

div {
  border: 1px solid green;
}

.sec {
  height: 250px;
  padding-top: 7%;
}

.backtotop {
  width: 61px;
  height: 61px;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  cursor: pointer;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="col-md-12 header">
<p> Header Section </p>
</div>

<img src="image.png" class="backtotop"  width="50px" height="50px">

<div class="col-md-12 sec">
<p> Section 1 </p>
</div>

<div class="col-md-12 sec">
<p> Section 2 </p>
</div>

<div class="col-md-12 sec">
<p> Section 3 </p>
</div>

标签: htmlcsstwitter-bootstraptwitter-bootstrap-3bootstrap-4

解决方案


如果您确定该img标签出现在每个页面上,您可以使用以下“hacky”CSS 来提供margin-top

.header ~ img.backtotop + div {
    margin-top: 2%;
}

.header {
  z-index: 200;
  top: 0;
  width: 100%;
  height: 70x;
  position: fixed;
  background-color: #fbfcfe;
}

.header~img.backtotop+div {
  margin-top: 2%;
}

div {
  border: 1px solid green;
}

.sec {
  height: 250px;
  padding-top: 7%;
}

.backtotop {
  width: 61px;
  height: 61px;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  cursor: pointer;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="col-md-12 header">
  <p> Header Section </p>
</div>

<img src="image.png" class="backtotop" width="50px" height="50px">

<div class="col-md-12 sec">
  <p> Section 1 </p>
</div>

<div class="col-md-12 sec">
  <p> Section 2 </p>
</div>

<div class="col-md-12 sec">
  <p> Section 3 </p>
</div>


推荐阅读