How can I select the first of the highest h*
elements present in a DOM?
Something like
(h1, h2, h3, h4, h5, h6):first-of-ordered-set
I.e. if a DOM tree has, in this order, h2
, h3
, h1
, h2
, h1
, it would select the first h1
;
and if the DOM has h3
, h3
, h2
, h2
, h4
, it would select the first h2
.
Let's assume h*
elements are not nested.
I suspect CSS doesn't have that power, right?
Somethink potentially usable: https://css-tricks.com/extremely-handy-nth-child-recipes-sass-mixins/
Edit: Why I want it: A CMS system takes this "first top heading" as a title of the document (post, page, ...). But it leaves it in the page. And then it shows the title twice - once as the post title and once in the body. JavaScript is removed. The top h*
level may differ.
I found something. CSS can't do it. Yet.
W3C is drafting new features:
.post-content:has(h1, h2, h3, h4, h5, h6)
Together with :not()
, this will allow what I need:
.post-content:has(h1) h1:first-of-kind,
.post-content:not(:has(h1)) h2:first-of-kind,
.post-content:not(:has(h1,h2)) h3:first-of-kind,
...
There's a catch - the :not()
currently can only have a single "simple selector". If it supported more, then it would be achievable even without :has
.
Greetings to the future readers, I hope it worked out. For now, I am leaving this open, maybe someone will figure out with CSS 3.1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With