I have div1 in this I have more <div>
s and <p>
s and I only want to select the <p>
in this <div>
and not in the other div
s
I tried the CSS :last-child
selector, but it selected also the last <p>
s in the other div.
How can I do that?
This is a sample of my code:
<div id="div1">
<div class="div2"><p>text</p></div>
<div class="div3"><p>text</p></div>
<div class="div4"><p>text</p></div>
<p>select only me</p>
</div>
You want to use the immediate children (>
) selector along with the :last-child
pseudo-class. This selects only p
elements that are "first-level" (not nested) children of #div1
and then selects only the last of those elements. See below:
#div1 > p:last-child {
color: red;
}
<div id="div1">
<div class="div2"><p>text</p></div>
<div class="div3"><p>text</p></div>
<div class="div4"><p>text</p></div>
<p>select only me</p>
</div>