how to chain CSS class selectors , which having multiple parent class?

796 Views Asked by At

if HTML is like:

-section1
--h1
--h2
--h3
--section2
--h1
--h2
--h3
-section3
--h1
--h2
--h3
--section4
--h1
--h2
--h3

what should we do if we want to give section1, section2, section3 same style and section4 different style ? in short code.

I wrote the code like

.section1 .h1,
.section1 .h2,
.section1 .h3,
.section2 .h1,
.section2 .h2,
.section2 .h3,
.section3 .h1,
.section3 .h2,
.section3 .h3,{
     color: blue;
}

but its too long and looking bad, is there any short way to write this.

2

There are 2 best solutions below

0
tacoshy On BEST ANSWER

The shortest vanilla CSS code is by selecting all elements that start with section by using the [class^="..."] attribute selector. Then overwrite the styles for section 4 specifically:

[class^="section"] h1,
[class^="section"] h2,
[class^="section"] h3 {
  color: blue;
}

.section4 h1,
.section4 h2,
.section4 h3 {
  color: red;
}
<section class="section1">
  This is Section 1
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</section>
<section class="section2">
  This is Section 2
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</section>
<section class="section3">
  This is Section 3
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</section>
<section class="section4">
  This is Section 4
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</section>

Alternatively, you can also use a Preprocessor like SASS:

[class^="section"] {
  h1, h2, h3 {
    color: blue;
  }
}

.section4 {
  h1, h2, h3 {
    color: red;
  }
}
0
Temani Afif On

You can do like below as well:

[class^="section"]:not(.section4) :is(h1,h2,h3) {
  color: blue;
}
<section class="section1">
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</section>
<section class="section2">
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</section>
<section class="section3">
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</section>
<section class="section4">
  <h1>Headline 1</h1>
  <h2>Headline 2</h2>
  <h3>Headline 3</h3>
</section>