I'm wondering if it is possible to target the last element of a particular type in CSS, knowing that there is no hierarchy so I can't use: the last-child CSS selector.
I want to apply a red font color to the last <p>
tag following each <h1>
tag.
The HTML is composed of one <h1>
tag followed by multiple (number may vary) <h1>
tags, as shown in the code below
I want to do this only with CSS! (no JS or SCSS ...)
<body>
<h1>hhhhhhhhh</h1>
<p>ppppp</p>
<p>ppppp</p>
<h1>hhhhhhhhh</h1>
<p>ppppp</p>
<p>ppppp</p>
<p>ppppp</p>
<h1>hhhhhhhhh</h1>
<p>ppppp</p>
<p>ppppp</p>
<p>ppppp</p>
<p>ppppp</p>
I tried :
h1 ~ p:last-of-type {
color: red;
}
but then it only selects the very last p, which is logical and understandable
I also tried this :
h1 ~ p:nth-last-of-type(3n) {
color: blue;
}
it works only when I have 3 'p' tags in each 'h1' tag
I think this is what you want:
p:has(+ h1), h1 ~ p:last-of-type {
color: red;
}
<body>
<h1>hhhhhhhhh</h1>
<p>ppppp</p>
<p>ppppp</p>
<h1>hhhhhhhhh</h1>
<p>ppppp</p>
<p>ppppp</p>
<p>ppppp</p>
<h1>hhhhhhhhh</h1>
<p>ppppp</p>
<p>ppppp</p>
<p>ppppp</p>
<p>ppppp</p>
EDIT: As Mihai pointed out, this is not a good idea because of browser compatibility. We need a previous sibling selector, which is not here yet...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments