1

How can I style :nth-child(4n) even with the element is nested inside a div, example here is p inside 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>
Vucko
  • 20,555
  • 10
  • 56
  • 107
Rachid O
  • 13,013
  • 15
  • 66
  • 92

2 Answers2

1

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>
Yash Yadav
  • 659
  • 4
  • 14
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>
Serge Andreev
  • 300
  • 1
  • 5