skip to Main Content

I’m trying to slightly modify the styles of a block formatting plugin in WordPress by overriding them in my own theme stylesheet. I use Sass but I’m new to it.

Pasting all of the selectors right out of Developer Tools works, but I know that’s not the elegant/modular way to do it:

.an-accordion.an-accordion--v2.an-accordion.an-accordion--design-basic .an-accordion__heading { 
    color: gold 
}

What’s the right way to do this in Sass? I’ve tried something like this:

.an-accordion {
    &--v2 {
        &--design-basic {
            &__heading {
                color: gold;
            }
        }
    }
}

but it doesn’t work. I can tell I’m missing something about the way .an-accordion repeats.

2

Answers


  1. BEM is about blocks, elements, and modifiers. Block scope is the biggest one, the element is some part inside the block and the modifier is optional and represents the status of your block-element. In Sass you can nest elements if they are parent and children and you don’t need to repeat the parent element, in your stlesheet, if the beginning of your property is the same for both parent and child, but if the beginning is different you must repeat.

    In a html like this:

    <div class=" an-accordion an-accordion--v2 .an-accordion--design-basic .an-accordion__heading"></div>
    

    You could have some scss code like this:

        .an-accordion{
            color: #000;
    
          &__heading{
             background-color: tomato;
           }
    
          &--v2{
             font-weight: bold;
           }
    
           &--design-basic{
              border: none;
           }
        }
    
    Login or Signup to reply.
  2. You can use the power of local scoped string variables $something:... combined with the power of string interpolation #{...} and combine it with the current selector string & to create a compound selector for any combination of block, element, and modifier. Which I think is quite nice and readable:

    .an-accordion {
      $modifier-v2: #{&}--v2;
      $modifier-design-basic: #{&}--design-basic;
      $element-heading: #{&}__heading;
    
      &#{$modifier-v2}#{$modifier-design-basic} {
        #{$element-heading} {
          color: gold;
        }
      }
    }
    

    which will result in:

    .an-accordion.an-accordion--v2.an-accordion--design-basic .an-accordion__heading {
      color: gold;
    }
    

    I tried it out on sassmeister.com

    Note that I omitted the duplicated .an-accordion class in the selector; if this is important for you to increase the specifity you can insert it with #{&}.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search