CSS how to select first element of consecutive same elements

Is it possible to select the first element of consecutive same elements and maybe change the background-color. Only the first element should be selected if there are multiple elements. If there is only one element it should also be selected. I prepared an example where I want to highlight all first p elements of consecutive p element sequences in the div. I tried fiddling around with :has() and :not() but couldn't get it to work, any help would be appreciated
<div>
<p>Should be highlighted</p>
<p>Lorem ipsum dolor sit.</p>
<p>Lorem ipsum dolor sit.</p>
<div>DIV: Lorem ipsum dolor sit.</div>
<p>Should be highlighted</p>
<div>DIV: Lorem ipsum dolor sit.</div>
<p>Should be highlighted</p>
<p>Lorem ipsum dolor sit.</p>
</div>
<div>
<p>Should be highlighted</p>
<p>Lorem ipsum dolor sit.</p>
<p>Lorem ipsum dolor sit.</p>
<div>DIV: Lorem ipsum dolor sit.</div>
<p>Should be highlighted</p>
<div>DIV: Lorem ipsum dolor sit.</div>
<p>Should be highlighted</p>
<p>Lorem ipsum dolor sit.</p>
</div>
8 Replies
Jochem
Jochem2mo ago
:first-of-type and its sibling :nth-of-type should do what you want
Chris Bolson
Chris Bolson2mo ago
div + p{
background: hotpink;
}
div + p{
background: hotpink;
}
would get you the first <p> after each div. However, that wouldn't get you the inital <p> (unless it had a <div> before it. You could of course get that with the :first-of-type selector but this might not always be the case.
Mannix
Mannix2mo ago
with this html try
p:first-child,
div + p {
background: red;
}
p:first-child,
div + p {
background: red;
}
tibbe09
tibbe092mo ago
First of all thanks for the help. I will try fiddling around with your suggestions. However the selector should not be related to the div since instead of div's it could be possible that there are other elements inbetween. I'd like to select each element (in this example p but it could also be something else or class related) that has no previous direct sibling of the same type or class...
Mannix
Mannix2mo ago
i feel you are asking for impossible here
Jochem
Jochem2mo ago
yeah, that's not really possible with CSS not that level of flexibility at least You could try something like :not(p) + p (or :not(.class) + .class) but that would only work for p of .class and not in the generic case also wouldn't be able to check for if there's multiples of the same type of element and only work then
tibbe09
tibbe092mo ago
Thank you all for your help and special thanks to @Jochem after his comment I came up with this selectors for my use case :nth-child(1 of p), :not(p) + p I think this selectors will work for my use case and 'p' can also be replaced with a class
Jochem
Jochem2mo ago
cool! Glad to help 🙂