How to select only first two children of a parent (not every first and every second child). In a .scss
mixin using nth:child
selector?
Here is my code and it doesn't work because it selects every second div
. But I need to select only col_l
as a :nth-child(1)
and col_r
as a :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 { }
}
How to select only the first and only the second divs? Not every.
You need to add the child combinator >
to the selectors in your mixin to ensure you actually select just the children of #section
and not any further descendants:
@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;
}
}