0

In CSS, if I want to style 3 sub-classes of a given class, is there a short-hand way of doing that in a manner where the root class does not have to be repeated for each sub-class?

For example, let say I have this html:

<div class="parent1">
    <div class="subClass1">Sub-Class-1</div>
    <div class="subClass2">Sub-Class-2</div>
    <div class="subClass3">Sub-Class-3</div>
    <div class="subClass4">Sub-Class-4</div>
    <div class="subClass5">Sub-Class-5</div>
    <div class="subClass6">Sub-Class-6</div>
</div>

<div class="parent2">
    <div class="subClass1">Sub-Class-1</div>
    <div class="subClass2">Sub-Class-2</div>
    <div class="subClass3">Sub-Class-3</div>
    <div class="subClass4">Sub-Class-4</div>
    <div class="subClass5">Sub-Class-5</div>
    <div class="subClass6">Sub-Class-6</div>
</div>

I want to make sub-classes 1, 3, 6 of parent1 red (without effecting the parent2 sub-classes). The way I'd do this is in CSS is:

.parent1 .subClass1,
.parent1 .subClass3,
.parent1 .subClass6
{
    color: red;
}

Is there a syntax in CSS where I can do something like this instead:

.parent1 (.subClass1, .subClass3, .subClass6)
{
    color: red;
}

... so that the parent1 class only has to be typed once?

Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
  • 2
    No, not in CSS. You might want to look into CSS preprocessors such as LESS or SASS. – CBroe Sep 05 '17 at 11:14
  • 2
    In navitve CSS, no. In a precompiler like LESS or SASS, yes, as you can do `.class1 { .class2, .class3, .class3 { /* styles */ } }` – Mitya Sep 05 '17 at 11:14
  • I wonder can't you just use `nth-child` on this. – raina77ow Sep 05 '17 at 11:15
  • Of course, for multiple `parentX` classes, you could use the attribute selector to target all elements with a class that _starts with_ `parent` in one go ... (https://stackoverflow.com/q/3338680/1427878) – CBroe Sep 05 '17 at 11:15
  • 2
    [:matches](https://css-tricks.com/almanac/selectors/m/matches/) – bkis Sep 05 '17 at 11:24
  • 1
    In fact, it is in [Selectors Level 4](https://drafts.csswg.org/selectors-4/#matches): `.parent1 :matches(.subClass1, .subClass3, .subClass6)`. Unfortunately, it works currently only in Safari. – Ilya Streltsyn Sep 05 '17 at 11:24
  • Ah, :matches is exactly what I'm looking for. I will [wait for support](http://caniuse.com/#feat=css-matches-pseudo). – Lonnie Best Sep 05 '17 at 11:32

1 Answers1

1

Not the way you describe, but in your specific example you can use nth-child to style every odd child:

.parent1 div:nth-child(odd) {

}

Or if each of the classes you want to target has text in common you can use an attribute selector:

.parent1 div[class*=subClass] {

}

That would target all children of parent1 that has subClass somewhere in its class. So in your case would select all children.