How can I apply styles to multiple classes at once?

Viewed 433762

I want two classes with different names to have the same property in CSS. I don't want to repeat the code.

.abc {
   margin-left:20px;
}  
.xyz {
   margin-left:20px;
}
<a class="abc">Lorem</a>
<a class="xyz">Ipsum</a>

Since both classes are doing the same thing, I should be able to merge it into one. How can I do that?

8 Answers
.abc, .xyz { margin-left: 20px; }

is what you are looking for.

You can have multiple CSS declarations for the same properties by separating them with commas:

.abc, .xyz {
   margin-left: 20px;
}

If you use as following, your code can be more effective than you wrote. You should add another feature.

.abc, .xyz {
margin-left:20px;
width: 100px;
height: 100px;
} 

OR

a.abc, a.xyz {
margin-left:20px;
width: 100px;
height: 100px;
} 

OR

a {
margin-left:20px;
width: 100px;
height: 100px;
} 

just seperate the class name with a comma.

.a,.b{
your styles
}

And if you have set these classes with their parents before, you should set them with parents (repeat each time) again as below:

parent .abc, parent .xyz

Using CSS pseudo-classes :is (previously :any and :matches) and :where, you can use comma to match multiple classes on any level.

At the root level, :is(.abc, .xyz) and .abc, .xyz function almost identically. However, :is allows matching only a part of the selector without copying the whole selector multiple times.

For example, if you want to match .root .abc .child and .root .xyz .child, you can write code like this:

.root :is(.abc, .xyz) .child {
   margin-left: 20px;
}  
<div class="root">
  <a class="abc">
    <span class="child">Lorem</span>
  </a>
  <a class="xyz">
    <span class="child">Ipsum</span>
  </a>
</div>

The difference between :is and :where is that :where is ignored when calculating specificity of the selector:

  • specificity of .root :is(.abc, .xyz) .child = specificity of .root .abc .child
  • specificity of .root :where(.abc, .xyz) .child = specificity of .root .child

Both pseudo-classes accept a forgiving selector list, meaning that if one selector fails to be parsed (due to unsupported syntax, either too new, too old or just incorrect), the other selectors would still work. This makes :is useful even at the root level, because it allows combining selectors using modern CSS features without fear that one selector will break the rest.

P.S. This question answers a more difficult variation of the question, but Google returns this page on too many queries, so I think this information will be relevant here.

There is also a way to use @extend to achieve this with SCSS.

Related