Search code examples
cssbem

BEM - Where to include modifiers for specific pages?


I am trying to use BEM naming convention and having some slight difficulty in deciding where to include a modifier for a specific page.

For example, say I have an orange button:

<button class="btn btn-orange">Button A</button>

My project has 3 different pages:

 - pageA.html - pageA.scss
 - pageB.html - pageB.scss
 - pageC.html - pageC.scss

On pageB.html the button should have a margin-top:30px. Is it correct to write the modifier this way:

.btn {
  padding: 5px 20px;
  background: orange;
  margin: 0

  &--margin-top {
    margin-top: 30px;
  }
}

And what is the best way to include a modifier like that only for a specific page? In this case that would be for pageB.html. Should I include that modifier inside the pageB.scss or .buttons.scss?


Solution

  • I think you're confusing two concepts here - BEM, which is Naming Convention with the problem of structuring your projects. Both have nothing to do with each other, and I think BEM is not opinionated in terms of structuring your SASS files.

    But, there's a couple of questions you ask here:

    1. Is it correct to write the modifier this way? - it is correct if you want to stick to BEM convention, although I would say, the name you picked .btn--margin-top might not be very fortunate in a long term - imagine, you'll want to include another btn modifier with margin-top property set to, let's say 40px. How will you name it?
    2. What is the best way to include a modifier like that only for a specific page? - These CSS classes you are usually not making for specific page. Whole point of BEM is to enable you, to write more modular CSS, and having this in mind you should use these CSS classes, by assigning them to your Blocks/Elements/Modifiers respectively. Trick here is to determine what is a block/element/modifier in your markup. What you'll achieve by this is reusable CSS, so you can quickly apply same css, by adding BEM classes.
      Think in terms of Blocks or Components, NOT pages. You want to use it only on pageB - just add btn--margin-top class to your pageB markup.
    3. Should I include that modifier inside the pageB.scss or .buttons.scss? - it depends on how you structure your project, and I would say that usually, buttons and other UI elements, are in most cases common to whole website/webapp, so there is no need of having them "attached" to specific page (which concept I think you need to drop, if you want to take full advantage of BEM). Besides, whatever suits you will be good for you, and unless you're not working within a team of developers, just stick to your own method, so you'll know in future where to look for things.