【问题标题】:using nth-child() non recursive? [duplicate]使用 nth-child() 非递归? [复制]
【发布时间】:2015-10-30 19:40:12
【问题描述】:

是否可以使用parent child:nth-child() 并且只适用于儿童?

html 如下:

<body>
    <div>div 1</div>
    <div>
        div 2
        <div>div 2.1</div>
        <div>div 2.2</div>
    </div>
</body>

我想用 CSS 选择:div 1 &amp; div 2,我用过:

body div:nth-of-type(1) {
    background: red;
    color: white;
}

body div:nth-child(2) {
    background: blue;
}

但是div 2.1 &amp; 2.21 也被选中了。 JSFiddle

是否可以进行非递归选择?如果不是,我猜唯一的解决方案是 clases 或 id's ..

【问题讨论】:

    标签: html css


    【解决方案1】:

    您可以在bodydiv 之间放置&gt; 以仅选择body直接 子代:

    body > div:nth-of-type(1) {
        background: red;
        color: white;
    }
    
    body > div:nth-child(2) {
        background: blue;
    }
    <body>
        <div>div 1</div>
        <div>
            div 2
            <div>div 2.1</div>
            <div>div 2.2</div>
        </div>
    </body>

    【讨论】:

      【解决方案2】:

      您可以使用“>”字符来表示父子选择器。由于默认情况下 2.1 和 2.2 是透明的,这并不能解决着色问题,因此您应该为它们设置不同的样式:

      https://jsfiddle.net/evccpeeL/1/

      div {
          background: white;
      }
      
      body > div:nth-of-type(1) {
          background: red;
          color: white;
      }
      
      body > div:nth-child(2) {
          background: blue;
      }
      

      【讨论】:

        【解决方案3】:

        您实际上不需要在这里使用伪类。

        您可以单独使用直接子选择器&gt; 来做到这一点

        body > div {
          background: red;
          color: white;
        }
        body > div > div {
          background: blue;
          color: white;
          padding-left: 1em;
        }
        <body>
          <div>div 1</div>
          <div>
            div 2
            <div>div 2.1</div>
            <div>div 2.2</div>
          </div>
        </body>

        你可能会发现这篇文章很有用The 30 CSS Selectors you Must Memorize

        【讨论】:

        • 文章很棒,感谢文档!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-26
        • 2018-07-30
        • 2013-04-04
        • 2012-10-04
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        相关资源
        最近更新 更多