-1

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Green
  • 28,742
  • 61
  • 158
  • 247

1 Answers1

3

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;
    }
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 1
    That's the answer. I would also suggest using `nth-of-type` instead of `nth-child` in such situations in case you need an element before or in between the two divs. It's more bulletproof that way. – Alexander Futekov Jan 31 '15 at 06:09