偶数和奇数级别儿童的选择器

blo*_*k14 7 css css-selectors

选择偶数和奇数级孩子的正确选择器是什么?

我想简化我当前的CSS,同时允许无限级别,而无需在CSS中手动编写它们.

.box {
    max-width:100%;margin:25px 0px;padding: 15px;
    border:#d1ddbd solid  2px;
    background-color:#f3fae8;
}

.box > .box {
    border:#d1ddbd solid  1px;
    background-color:#fff;
}

.box > .box > .box {
    border:#d1ddbd solid  1px;
    background-color:#f3fae8;
}

.box > .box > .box > .box {
    border:#d1ddbd solid  1px;
    background-color:#fff;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

在CSS中,除了坐下来编写规则外,没有其他方法可以做到这一点。编写十个规则并把您带到十个嵌套级别并没什么大不了的。您的替代方法是花更多的时间编写JS来添加类,或者使用后端添加类,或者与SASS宏战斗,这些花费的时间都比这值得。

.box {
  max-width: 100%;
  margin:    25px 0px;
  padding:   15px;
  border:    #d1ddbd solid 2px;
}

.box > .box {
  border-width: 1px;
}

.box,
.box > .box > .box, 
.box > .box > .box > .box > .box, 
.box > .box > .box > .box > .box > .box > .box,
.box > .box > .box > .box > .box > .box > .box > .box > .box {
    background-color:#f3fae8;
}

.box > .box, 
.box > .box > .box > .box, 
.box > .box > .box > .box > .box > .box,
.box > .box > .box > .box > .box > .box > .box > .box,
.box > .box > .box > .box > .box > .box > .box > .box, .box > .box {
    background-color:#fff;
}
Run Code Online (Sandbox Code Playgroud)


小智 1

您现在可以使用容器查询来做到这一点!仅仅花了8年时间。

基本上,您使用容器查询来定位特定样式,并在其中切换样式本身:

layering {
  container-name: layering;
  --depth-is-odd: true;
}

@container layering style(--depth-is-odd: true) {
  .layering {
   // styles for odd levels of nesting
    --depth-is-odd: false;
  }
}

@container layering style(--depth-is-odd: false) {
  .layering {
   // styles for even levels of nesting
    --depth-is-odd: true;
  }
}
Run Code Online (Sandbox Code Playgroud)