skip to Main Content

I am using the BEM method together with SASS and I have a big doubt.

I have this HTML

<section class="section1">
<p class="section1__tittle"></p>

</section>

<section class="section2">
<p class="section2__tittle"></p> ...

</section>

This CSS :

.section1{}
.section2{}
.section1__tittle, .section2__tittle{
 // as both headings share the same style, I apply it to each other
}

Now, how can I replicate applying styles to both titles, following BEM+SASS?

SASS

.section1{
 &__tittle{}
}
.section2{
 &__tittle{}
}

Because following this structure, I have to repeat it twice

The solution is to put a shared class or is there a way in SASS to make a .section1__tittle, .section2__tittle respecting the BEM methodology? thanks

2

Answers


  1. If .section1__title and .section2__title are equal, why don’t you merge it into one class?

    -html

    <section class="section1">
      <p class="title"></p>
    </section>
    
    <section class="section2">
      <p class="title"></p> ...
    </section>
    

    -css

    .title { }
    .section1 { }
    .section2 { }
    

    If you want to add some different properties to .title for .section1, .section2, do it in .section1, .section2 like below.

    .title { }
    
    .section1 {
      .title { }
    }
    
    .section2 {
      .title { }
    }
    

    It’s not repeating, Ok?

    Thanks.

    Login or Signup to reply.
  2. One way is to select .section1 and .section2 at the same time and use the & to add the "__tittle" part.

    .section1, .section2{
     /* styles */
     &__tittle{/* styles */}
    
     &__more-shared{/* styles */}
    
     &__blablabla{/* styles */}
    }
    

    That works because the ampersand & adds on to each of the parent selectors, so the code above gives you the exact same selectors as this:

    .section1, .section2{/* styles */}
    
    .section1__tittle, .section2__tittle{/* styles */}
    
    .section1__more-shared, .section2__more-shared{/* styles */}
    
    .section1__blablabla, .section2__blablabla{/* styles */}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search