【问题标题】:css - Select every element depending on the parity of amount of parents ( CSS or Less but no JS )css - 根据父母数量的奇偶性选择每个元素(CSS或Less但没有JS)
【发布时间】:2021-02-19 05:36:24
【问题描述】:

[我知道我可能没有很好地解释标题中的问题。 ]

所以,我正在处理一个样式表,其中有两个自定义元素(<grid><box>)是弹性框,并在 flex-direction 中交替出现,例如:

<box>             <!-- flex-direction: column -->
  <grid>           <!-- flex-direction: row -->
    <box></box>     <!-- flex-direction: column -->
    <box></box>     <!-- flex-direction: column -->
  </grid>
  <box>            <!-- flex-direction: row -->
    <grid></grid>   <!-- flex-direction: column -->
  </box>
</box>

在较少的情况下,我最好的解决方案是:

grid, box { display: flex }
body {
 > grid, > box {
   flex-direction: column;
 > grid, > box {
   flex-direction: row;
 > grid, > box {
   flex-direction: column;
   // Etc...
 }}}
}

这很糟糕,css中是否有类似下面的代码?

grid, box { display: flex }
body > grid:parents(even), body > box:parents(even) { flex-direction: column }
body > grid:parents( odd), body > box:parents( odd) { flex-direction: row }

编辑:body > nth-child() 不起作用。

代码:

body > grid:nth-child(even),
body > box:nth-child(even) {
  flex-direction: column;
}

body > grid:nth-child(odd),
body > box:nth-child(odd) {
  flex-direction: row;
  1. body &gt; element:nth-child(odd)只选择body的第一个直接子节点,应该是body element:nth-child(odd)

  2. 我在问题开头的 HTML 示例在修改以解决问题 1 时使用上面的代码如下所示。

<box>             <!-- flex-direction: column -->
  <grid>           <!-- flex-direction: row -->
    <box></box>     <!-- flex-direction: column -->
    <box></box>     <!-- flex-direction: row -->
  </grid>
  <box>            <!-- flex-direction: column -->
    <grid></grid>   <!-- flex-direction: row -->
  </box>
</box>

这不是一回事。

【问题讨论】:

    标签: html css flexbox css-selectors less


    【解决方案1】:

    除非我遗漏了一些明显的东西,否则像这样简单的东西应该可以达到同样的效果:

    grid,
    box {
      display: flex
    }
    
    body > grid:nth-child(even),
    body > box:nth-child(even) {
      flex-direction: column;
    }
    
    body > grid:nth-child(odd),
    body > box:nth-child(odd) {
      flex-direction: row;
    

    }

    您可以使用nth-child 来确定父元素的even-ness 或odd-ness 并从中派生规则。

    【讨论】:

    • 10/10,我也可以使用 less 来缩小它:body{&gt;box,&gt;grid{&amp;:nth-child(odd){/* odd code */}&amp;:nth-child(even){/* even code */}}}
    • 我刚刚发现了 2 个问题,1. body /* whatever */ 而不是 body &gt; /* whatever */ 2. 元素的子元素自己交替弯曲方向。我将在问题中对此进行更多解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    相关资源
    最近更新 更多