如何在与nth-child?的mixin中仅选择父母的前两个孩子?而不是每一个和第二个

时间:2015-01-31 05:50:47

标签: css css3 css-selectors sass compass

如何只选择父母的前两个孩子(不是每个第一个和每个第二个孩子)。在.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?并非每一个。

1 个答案:

答案 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;
    }
}