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;
}
The new :is() CSS pseudo-class can do it in one selector:
:is(h1, h2, h3, h4, h5, h6) {
color: red;
}
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;
}
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.
To tackle this with vanilla CSS look for patterns in the ancestors of the h1..h6
elements:
<section class="row">
<header>
<h1>AMD RX Series</h1>
<small>These come in different brands and types</small>
</header>
</header>
<div class="row">
<h3>Sapphire RX460 OC 2/4GB</h3>
<small>Available in 2GB and 4GB models</small>
</div>
If you can spot patterns you may be able to write a selector which targets what you want. Given the above example all h1..h6
elements may be targeted by combining the :first-child and :not pseudo-classes from CSS3, available in all modern browsers, like so:
.row :first-child:not(header) { /* ... */ }
In the future advanced pseudo-class selectors like :has(), and subsequent-sibling combinators (~
), will provide even more control as Web standards continue to evolve over time.
for n in 1..6
h{n}
font: 32px/42px trajan-pro-1,trajan-pro-2;
You can also use PostCSS and the custom selectors plugin
@custom-selector :--headings h1, h2, h3, h4, h5, h6;
article :--headings {
margin-top: 0;
}
Output:
article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
margin-top: 0;
}