Search code examples
htmlcsssassbem

How to Handle Variant in SCSS using BEM Methodology


I'm trying to figure out this stupid yet annoying issue that I face up with BEM. Currently for my application, I follow the BEM methodology for creating UI Elements. For instance :

<div class="card">
    <h2 class="card__title">Sample Title </h2>
    <h3 class="card__subtitle"> Sub Title </h3>
    <button class="card__action"> Action Button </button>
</div>

The scss for this will be :

.card{
     &__title{color:red}
     &__subtitle{color:violet}
     &__subtitle{bakground:black}
}

Now if I need to add a new variant of the card, I will be adding it as "card--modifier".

.card{
    &--variant{background-color:white}
    &__title{color:red}
    &__subtitle{color:violet}
    &__subtitle{bakground:black}
}

Now, without breaking this nesting in scss, how can I modify the properties of child under the variant ?


Solution

  • In situations like this I don't make a big fuss about repeating a classname or two.

    If in case of card--variant you want for example the card__title to have a blue font color, you could just add the necessairy changes at the end of your rules (order is important, keep your specifity low and add special cases at the end)

    .card {
       &__title { color: red; }
       &__subtitle { color: violet; }
       &__action { background-color: black; }
    
       &--variant {
           .card__title { color: blue; }
       }
    }
    

    If for some reason you adamantly don't want to duplicate a name, you can capture the block-level name in a variable and use string interpolation:

    .card {
       $block: &;
       &__title { color: red; }
       &__subtitle { color: violet; }
       &__action { background-color: black; }
    
       &--variant {
           .#{$block}__title { color: blue; }
       }
    }