0

I want to add a bottom margin to the last paragraphs. It should be selected if there are other element types after the paragraph. For visual purpose I will use red backgrounds in my example. I would like the <p> before the second <h2> to be also red. I can't see how to select this element. :nth-child() will not work, as the number of elements could vary. Thank you!

p:last-of-type {
  background: red;
}
<h2>Title</h2>
<p>This should not be red</p>
<p>This should be red</p>
<h2>Title</h2>
<p>This should not be red</p>
<p>This should be red</p>
Emiel B
  • 1
  • 2
  • You can not select an element based on what might or might not come after it. You could select `h2` elements that come after a `p` though (adjacent sibling combinator), and apply a margin-top to those instead. – CBroe Apr 12 '22 at 08:15
  • @CBroe Yes, I think that could work for my use case. I will look into it. Thank you! – Emiel B Apr 13 '22 at 09:08

1 Answers1

-1

you can give them a shared class and control this class like this example

 .p_red {
     background-color : red;
    }
    <h2>Title</h2>
    <p>This should not be red</p>
    <p class = "p_red">This should be red</p>
    <h2>Title</h2>
    <p>This should not be red</p>
    <p class= "p_red">This should be red</p>
Gowtham
  • 1,557
  • 12
  • 24