Search code examples
csssassbem

How to Write Modifiers using Sass and BEM


I'm really confused with how to use scope with Sass and BEM convention.

I have the following code:

<div className="page">
   <div className="page__main-content">
    </div>
</div>

I have a condition that sometimes will convert the following code above to:

   <div className="page">
       <div className="page__main-content main-content--active">
        </div>
    </div>

Now I want to represent that in sass I did the following:

.page{
  &__main-content{
    min-height: 100vh;
    width: calc(100% - 20em);
    margin-left: 10.9em;
    &--active {
      width: calc(100% - 5em);
    }
  }
}

But the width does not change. Looking at the transpiled code it looks like this:

page__main-content main-content--active

How would I show this in Sass?

I also want to override the width (at both active and inactive state to this)

@media (max-width: 800px) {
  .page{
    &__main-content {
      width: 100% !important;
    }
  }
}

Solution

  • This is the way you should set it up in SASS:

    .page{
      &__main-content{
        min-height: 100vh;
        width: calc(100% - 20em);
        margin-left: 10.9em;
    
        &.main-content {
          &--active {
            width: calc(100% - 5em);
          }
        }
      }
    }
    

    This compiles to:

    .page__main-content {
      min-height: 100vh;
      width: calc(100% - 20em);
      margin-left: 10.9em;
    }
    .page__main-content.main-content--active {
      width: calc(100% - 5em);
    }
    

    You basically need to say .page__main-content WITH another class .main-content

    Here's the fiddle to show it working: https://jsfiddle.net/nbqfjcwh/

    Also, your React compiler should be compiling the className to class - which is why I think you're not seeing the results.