CSS样式:nth-​​child甚至嵌套元素

时间:2017-04-25 10:10:03

标签: html css

即使元素嵌套在div 中,我如何设置:nth-child(4n)样式,例如p内的div

p:nth-child(2) {
    background: red;
}
<p>The first paragraph.</p>
<div>
  <p>The second paragraph.</p>
</div>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

2 个答案:

答案 0 :(得分:0)

    .content *:nth-child(2) {
        background: red;
    }
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="content">
    <p>The first paragraph.</p>
    <div>
        <p>The second paragraph.</p>
    </div>
    <p>The third paragraph.</p>
    <p>The fourth paragraph.</p>

    <p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-child() selector.</p>
</div>

答案 1 :(得分:0)

body p:nth-child(2n) {
    background: red;
}
body div:nth-child(2n) p {
    background: red;
}
<body>
<p>The first paragraph.</p>
<div>
  <p>The second paragraph.</p>
</div>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<body>