我有简单的div
结构,因为我有7列float: left
。我想使用float: right
将:last-child
应用到最后一列,但它不起作用。
下面是HTML和CSS。
<div class="boc-practice-impact-main">
<div class="bocpi-header">Practice Impact</div>
<div class="bocpi-body-main">
<div class="bocpi-column">1</div>
<div class="bocpi-column">2</div>
<div class="bocpi-column">3</div>
<div class="bocpi-column">4</div>
<div class="bocpi-column">5</div>
<div class="bocpi-column">6</div>
<div class="bocpi-column">7</div>
<div class="clearfix"></div>
</div>
</div>
.boc-practice-impact-main {
width: 100%;
background-color: red;
}
.boc-practice-impact-main .bocpi-header {
width: 100%;
background-color: #49bad7;
line-height: 20px;
text-align: center;
margin-top: 3px;
}
.boc-practice-impact-main .bocpi-body-main {
width: 100%;
background-color: #333333;
line-height: 20px;
text-align: center;
margin-top: 3px;
}
.boc-practice-impact-main .bocpi-body-main .bocpi-column {
width: calc(100%/7 - 21px);
background-color: #f4f8fc;
float: left;
margin: 5px 21px 20px 0px;
padding: 5px;
min-height: 200px;
}
.business-outcome-main-div-new .bocpi-body-main .bocpi-column:last-child {
width: calc(100%/7 - 20px);
background-color: #ff0000;
float: right;
margin: 5px 0px 20px 0px;
padding: 5px;
min-height: 200px;
}
感谢您的解决方案。
答案 0 :(得分:3)
没有bocpi-column
元素是其容器的最后一个子元素。
<div class="clearfix"></div>
或<div class="bocpi-body-main">
是。
您的HTML无效。如果您使用过a validator,它会在您的代码中提醒您许多丢失的</div>
代码。
答案 1 :(得分:2)
没有last-child
类选择器,它将定位.bocpi-body-main
的最后一个子项。
在您的情况下,您可以通过删除<div class="clearfix"></div>
来解决此问题并使用基于CSS的明确修复,使用伪元素::after
.boc-practice-impact-main .bocpi-body-main::after { /* clearfix */
content: '';
display: block;
clear: both;
}
Stack snippets
.boc-practice-impact-main {
width: 100%;
background-color: red;
}
.boc-practice-impact-main .bocpi-header {
width: 100%;
background-color: #49bad7;
line-height: 20px;
text-align: center;
margin-top: 3px;
}
.boc-practice-impact-main .bocpi-body-main {
width: 100%;
background-color: #333333;
line-height: 20px;
text-align: center;
margin-top: 3px;
}
.boc-practice-impact-main .bocpi-body-main::after {
content: '';
display: block;
clear: both;
}
.boc-practice-impact-main .bocpi-body-main .bocpi-column {
width: calc(100%/7 - 21px);
background-color: #f4f8fc;
float: left;
margin: 5px 21px 20px 0px;
padding: 5px;
min-height: 200px;
}
.boc-practice-impact-main .bocpi-body-main .bocpi-column:last-child {
width: calc(100%/7 - 20px);
background-color: #ff0000;
float: right;
margin: 5px 0px 20px 0px;
padding: 5px;
min-height: 200px;
}
<div class="boc-practice-impact-main">
<div class="bocpi-header">Practice Impact</div>
<div class="bocpi-body-main">
<div class="bocpi-column">1</div>
<div class="bocpi-column">2</div>
<div class="bocpi-column">3</div>
<div class="bocpi-column">4</div>
<div class="bocpi-column">5</div>
<div class="bocpi-column">6</div>
<div class="bocpi-column">7</div>
</div>
</div>