Search code examples
htmlcsscss-selectors

How to select only the last <p> in a <div> with No class?


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 divs

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>

Solution

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