【问题标题】:How to select only first two children of a parent in a mixin with nth-child?, not every first and second如何在第n个孩子的mixin中只选择父母的前两个孩子?,而不是每个第一个和第二个
【发布时间】:2015-01-31 14:02:09
【问题描述】:

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

如何选择only第一个和only第二个div?不是每个。

【问题讨论】:

  • 我认为您的拼写错误可能会破坏其他内容 - .col-r { } 应该带有下划线 - .col_r { }

标签: css css-selectors sass compass


【解决方案1】:

您需要将子组合子 &gt; 添加到您的 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;
    }
}

【讨论】:

  • 这就是答案。我还建议在这种情况下使用nth-of-type 而不是nth-child,以防您在两个div 之前或之间需要一个元素。这样更防弹。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 2017-03-11
  • 2022-06-28
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多