Search code examples
sass

How to make h1, h2, h3 versions for a class with scss?


I want to define a class and write different styles for its h1, h2, h3 versions:

.title {
  color: red;
    
  &h1 {
    font-size: 18px;
  }
    
  &h2 {
    font-size: 16px;
  }
}

I expect the CSS output like this:

.title { 
  color: red; 
}
h1.title { 
  font-size: 18px; 
}
h2.title { 
  font-size: 16px; 
}

This is the CSS output I actually get:

.title {
  color: red;
}
.titleh1 {
  font-size: 18px;
}
.titleh2 {
  font-size: 16px;
}

Those headlines should also contain the class .title.


Solution

  • Using this QA as a reference, you'll need to use @at-root and a placeholder:

    .title {
      color: red;
    
        @at-root {
            h1#{&} {
                font-size: 18px;
            }
            
            h2#{&} {
                font-size: 16px;
            }
        }
    }
    

    Gives me this output:

    .title {
      color: red;
    }
    h1.title {
      font-size: 18px;
    }
    
    h2.title {
      font-size: 16px;
    }