Scss, nth-child & :not() 选择器



我对 scss 有点陌生,我对行容器中的行有这种基本样式。

.rows-container{
    border-bottom:2px ridge grey;
}
.row{
    height:30px;width:100%;
    &:hover div{
        background-color:lightgrey;
        }
    &:nth-child(odd){
        background: white;
        }
    &:nth-child(even){
        background: #e0e0e0;
        }
}

以下 HTML 非常简单:我省略了一些不重要的 HTML。

<div class="rows-container">
    <div class="row></div> //white
    <div class="row></div> //grey
    <div class="row></div> //white
    <div class="row></div> //grey etc...
</div>

但是现在我添加了子行

<div class="rows-container">
    {{each rows}}
        <div class="row"></div>           //parent row
        {{each childs}}
        <div class="subitem"></div>   //several rows from the same table which have a parent_id connected to the current row.
        {{#each}}
    {{#each}}
</div>

我打算在单击时切换子项。但是当没有子项可见时(子项有自己的颜色(,".rows"奇数/偶数就会搞砸。现在我认为这是因为第 n 个子奇数/偶数是在容器中的所有行/子项上计算的,而不仅仅是 .row(s(。有没有办法奇数/偶数样式 .rows,但从奇数/偶数旋转中排除 .subitems? 我在想也许有一种方法可以在 scss 中使用 :not((,但到目前为止我还没有成功。

使用:nth-of-type

所以你的代码应该是:

.row{
    height:30px;width:100%;
    &:hover div{
        background-color:lightgrey;
        }
    &:nth-of-type(odd){
        background: white;
        }
    &:nth-of-type(even){
        background: #e0e0e0;
        }
}

参考: https://css-tricks.com/almanac/selectors/n/nth-of-type/

.subitem:nth-of-type(even) {
  background: lightslategrey;
}
.subitem:nth-of-type(odd) {
  background: red;
}
<div class="subitem">subitem</div>
<div class="">subitem no class</div>
<div class="">subitem no class</div>
<div class="subitem">subitem</div>
<div class="subitem">subitem</div>
<div class="">subitem no class</div>
<div class="">subitem no class</div>
<div class="subitem">subitem</div>
<div class="">subitem no class</div>
<div class="">subitem no class</div>

正如我已经评论过的:如果你把你的.row变成<section>并保持兄弟姐妹(它们在同一水平(彼此相邻(而不是嵌套在.row内(作为<div>,你可以使用以下方法维护.row上的奇数/偶数序列:

部分:第n种(奇数(

使用:nth-of-type()选择器可以让您通过使用不同的标签来更好地控制,当战略性地使用时,将允许您专门针对标签。

演示

section:nth-of-type(odd) {
  background: rgba(0, 0, 0, .4)
}
section:nth-of-type(even) {
  background: rgba(200, 0, 0, .4)
}
<div class="rows-container">
  <section class="row">ROW1</section>
  <div>DIV</div>
  <section class="row">ROW2</section>
  <div>DIV</div>
  <div>DIV All divs are not children of any .row</div>
  <div>DIV All divs are siblings of the .row</div>
  <section class="row">ROW3</section>
  <div>DIV</div>
  <section class="row">ROW4</section>
  <div>DIV</div>
  <div>DIV</div>
  <section class="row">ROW5</section>
  <div>DIV</div>
  <section class="row">ROW6</section>
  <div>DIV</div>
  <div>DIV</div>
  <div>DIV</div>
</div>

最新更新