html - 当图像代码在它们之间使用组合器或任何其他方式时,如何仅从第一个 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>
解决方案
如果您确定该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>
推荐阅读
- android - 使用资源缩减和 Proguard 签署应用程序后应用程序崩溃
- swift - Xcode 的布局问题
- html - 我无法通过单击拼写检查图标检查文本区域输入中的拼写
- angularjs - 根据列表填充表字段 - AngularJS
- hyperledger-fabric - 从结构运行 make peer 命令时出错
- c# - 如何在 linq 中使用 where
- ios - iOS 服务工作者处理请求的方式是否与 Chrome/FF 不同?
- python - NameError: name 'test' is not defined ,当尝试在导入的模块/脚本 Python 3 中运行函数时
- sql - 在 DB2 中的选择查询中计算百分比
- python - 在给定变量的情况下访问 django 模板的字典?