如何在与 nth-child 的混合中 select 只有 parent 的前两个 children?,而不是每个第一个和第二个

How to select only first two children of a parent in a mixin with nth-child?, not every first and second

如何 select 只 child 一个 parent 的前两个 children(不是每个第一个和第二个 child)。在 .scss 混入中使用 nth:child select 或?

这是我的代码,它不起作用,因为它 select 每秒 div。但是我只需要 select 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 { }
}

如何select 第一个和第二个div?不是每个。

您需要将子组合器 > 添加到混入中的 selector 以确保您实际上 select 只是 #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;
    }
}