Search code examples
csscss-selectors

Can I target all <H> tags with a single selector?


I'd like to target all h tags on a page. I know you can do it this way...

h1,
h2,
h3,
h4,
h5,
h6 {
  font: 32px/42px trajan-pro-1,trajan-pro-2;
}

but is there a more efficient way of doing this using advanced CSS selectors? e.g something like:

[att^=h] {
  font: 32px/42px trajan-pro-1,trajan-pro-2;
}

(but obviously this doesn't work)


Solution

  • The new :is() CSS pseudo-class can do it in one selector.

    For example, here's how you could target all headings inside a container element:

    :is(h1, h2, h3, h4, h5, h6) {
        color: red;
    }
    

    Most browsers now support :is(), but keep in mind that most browsers made before 2020 didn't support it without a prefix, so be careful about using this if you need to support older browsers.

    In some cases, you may instead want to use the :where() pseudo-class, which is very similar to :is() but has different specificity rules.