如何只选择父母的前两个孩子(不是每个第一个和每个第二个孩子)。在.scss
mixin中使用nth:child
选择器?
这是我的代码,它不起作用,因为它选择每秒div
。但我只需选择col_l
作为:nth-child(1)
,将col_r
选为:nth-child(2)
。
HTML :
<section id="section" class="clearfix">
<div class="col_l"> <!-- this is div:nth-child(1) -->
<div class="title">
Left col
</div>
<div></div>
<div></div> <!-- this div is also selected as a :nth-child(2), but it is wrong -->
</div>
<div class="col_r"> <!-- this is div:nth-child(2) -->
<div class="title">
Right Col
</div>
</div>
</section>
.scss :
@mixin two-col($width-left, $width-right) {
@include clearfix;
div:nth-child(1) {
float: left;
width: $width-left;
}
div:nth-child(2) {
float: right;
width: $width-right;
}
}
#section {
@include two-col(714px, 237px);
background-color: #749675;
.col_l { }
.col-r { }
}
如何选择仅第一个和仅第二个div?并非每一个。
答案 0 :(得分:3)
您需要将子组合子>
添加到mixin中的选择器,以确保您实际只选择#section
的子项,而不是任何其他后代:
@mixin two-col($width-left, $width-right) {
@include clearfix;
> div:nth-child(1) {
float: left;
width: $width-left;
}
> div:nth-child(2) {
float: right;
width: $width-right;
}
}