michel lompret
michel lompret

Reputation: 317

Select multiple classes with same property

I have multiple classes like this with same property:

.class1 > div{
  background-color: red;
}

I try to reduce the CSS code with:

.class1, .class2, .class3 > div{
  background-color: red;
}

But it doesn't work properly, it only takes the last class in this case .class3.

Is there a way to properly do this?

Upvotes: 1

Views: 662

Answers (2)

Stickers
Stickers

Reputation: 78676

You will be able to use :matches pseudo-class in CSS Selectors Level 4.

:matches(.class1, .class2, .class3) > div {
  ...
}

It only works in certain browsers at the moment, e.g. latest Apple Safari.

For now, you will have to use the old syntax, :any with their respective prefix in Firefox and Chrome. Not supported in IE and Edge.

:-moz-any(.class1, .class2, .class3) > div { ... }
:-webkit-any(.class1, .class2, .class3) > div { ... }

:-moz-any(.class1, .class2, .class3) > div {
  background: aqua;
}
:-webkit-any(.class1, .class2, .class3) > div {
  background: aqua;
}
:matches(.class1, .class2, .class3) > div {
  background: aqua;
}
<div class="class1"><div>1</div></div>
<div class="class2"><div>2</div></div>
<div class="class3"><div>3</div></div>
<div class="class4"><div>4</div></div>
<div class="class5"><div>5</div></div>

Hopefully, the standard :matches will be available in all the major browsers in the near future. Other than that, please write the whole selectors for each one and separate them with commas:

.class1 > div,
.class2 > div,
.class3 > div {
  ...
}

References:

Upvotes: 3

Hunter Turner
Hunter Turner

Reputation: 6894

If you want the child div selected for each of the classes, you'll need to specify it with the selector for each class like so:

CSS

.class1 > div, .class2 > div, .class3 > div {
  background-color: red !important;
}

Single Selector (Wrong)

Selector For Each Class (Right)

Upvotes: 3

Related Questions