Rachid O
Rachid O

Reputation: 14052

CSS style :nth-child even nested elements

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>

Upvotes: 1

Views: 1738

Answers (2)

Yash Yadav
Yash Yadav

Reputation: 665

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>

Upvotes: 0

Serge Andreev
Serge Andreev

Reputation: 310

    .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>

Upvotes: 0

Related Questions