home
has-selector.md

The Has Selector in CSS

2022-08-28 4

This is a selector that I’ve been looking forward to for a long time!

The ability to trigger some css based on if something else is happening on the page is pretty useful.

One quick example that came up on my own site was to style the filenames I have above my code snippets.

It follows the format of:

<p>hoc.y</p>
<pre>
...
</pre>

I want to be able to style the p tags that have a pre that follows them. The other p tags should be left alone.

Now with the has selector this is possible!

p:has(+ pre) {
    font-style: italic;
    margin-bottom: 5px;
}

This will style just the p tags that are followed by a pre.

You can start using this but currently it is in the Chrome beta for version 105 and Firefox is still gated behind an about:config option but I haven’t been able to get it to work yet.

MDN link:

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

Chrome link:

https://www.google.com/chrome/beta/