0

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) <p> 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

Anass igli
  • 26
  • 3

2 Answers2

1

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>
  • p:has(+ h1) targets a p that has a h1 after it
  • h1 ~ p:last-of-type, as you said, targets the last one

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

PataFoos
  • 126
  • 1
  • 6
1

you can try putting every section in a div like this

<div>
  <h1>hhhhhhhhh</h1>
  <p>ppppp</p>
  <p>ppppp</p>
</div>
<div>
  <h1>hhhhhhhhh</h1>
  <p>ppppp</p>
  <p>ppppp</p>
  <p>ppppp</p>
</div>
<div>
  <h1>hhhhhhhhh</h1>
  <p>ppppp</p>
  <p>ppppp</p>
  <p>ppppp</p>
  <p>ppppp</p>
</div>

and css like this

h1 ~ p:last-of-type {
  color: red;
}

and that should work