I have some css code which adds margin to H1-H6 titles. I would like to see if there is a way to make this shorter and cleaner without repeating the same rule every time. Maybe with a variable.
Sorry but I'm new, I don't know if this can actually be done. Below I post some code that I have tried, they are fine but I do not think it is optimal as a practice. Is there a better way to do this? I believe that a better management of this problem can be useful on many other aspects concerning css.
I have tried this
.article-heading > div h1 { margin-bottom: 12px!important; }
.article-heading > div h2 { margin: 24px 0px 12px 0px!important; }
.article-heading > div h3 { margin: 24px 0px 12px 0px!important; }
.article-heading > div h4 { margin: 24px 0px 12px 0px!important; }
.article-heading > div h5 { margin: 24px 0px 12px 0px!important; }
.article-heading > div h6 { margin: 24px 0px 12px 0px!important; }
And this
.article-heading > div h2, .article-heading > div h3, .article-heading > div h4, .article-heading > div h5, .article-heading > div h6 { margin: 24px 0px 12px 0px!important; }
please try as following:
.article-heading>div h1 {
margin: 0px 0px 12px 0px!important;
}
.article-heading>div :is(h2, h3, h4, h5, h6) {
margin: 24px 0px 12px 0px!important;
}
<div class="article-heading">
<div>
<h1>Hello World!</h1>
<h2>Hello World!</h2>
<h3>Hello World!</h3>
<h4>Hello World!</h4>
<h5>Hello World!</h5>
<h6>Hello World!</h6>
</div>
</div>
new :is() CSS pseudo-class can do it in one selector.
above is the example how you could target all headings inside a container element.
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.