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
8 Replies
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.
with this html try
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...
i feel you are asking for impossible here
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 thenThank 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 classcool! Glad to help 🙂