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 1:

No, a comma-separated list is what you want in this case.

Solution 2:

If you're using SASS you could also use this mixin:

@mixin headings {
    h1, h2, h3,
    h4, h5, h6 {
        @content;
    }
}

Use it like so:

@include headings {
    font: 32px/42px trajan-pro-1, trajan-pro-2;
}

Edit: My personal favourite way of doing this by optionally extending a placeholder selector on each of the heading elements.

h1, h2, h3,
h4, h5, h6 {
    @extend %headings !optional;
}

Then I can target all headings like I would target any single class, for example:

.element > %headings {
    color: red;
}

Solution 3:

It's not basic css, but if you're using LESS (http://lesscss.org), you can do this using recursion:

.hClass (@index) when (@index > 0) {
    h@{index} {
        font: 32px/42px trajan-pro-1,trajan-pro-2;
    }
    .hClass(@index - 1);
}
.hClass(6);

Sass (http://sass-lang.com) will allow you to manage this, but won't allow recursion; they have @for syntax for these instances:

@for $index from 1 through 6 {
  h#{$index}{
    font: 32px/42px trajan-pro-1,trajan-pro-2;
  }
}

If you're not using a dynamic language that compiles to CSS like LESS or Sass, you should definitely check out one of these options. They can really simplify and make more dynamic your CSS development.

Solution 4:

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:

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