Search code examples
cssbem

CSS BEM - Convention for common class


I'm trying to refactor our styles with BEM convention. On our page, we got some elements which are written bold.

Let's say we got a startpage and a detailpage. Both pages contains some text elements. Often this elements has an extra class, which only contains

.block__element {
  font-weight: bold;
}
.block__element--modifier {
  font-weight: bold;
}

To avoid unneccessary code duplication, I'm asking myself how to refactor this best. Is it a good approach to define one common element (maybe in my main style.css)

.text--bold {
  font-weight: bold;
}

which I can use in all places where texts needs to be set bold? Or is there a better solution?

EDIT: I think mixes are the way to go. So as far as i understood I need to create a mix text--bold and apply it to every affected text element?


Solution

  • EDIT:

    BEM guidelines on DRY : https://cssguidelin.es/#dry

    Basically, you should not force yourself to hunt duplicated lines of code. But if a specific case is happening more than once, you can make use of a mixin.

    @mixin my-web-font() {
      font-family: "My Web Font", sans-serif;
      font-weight: bold;
    }
    
    .btn {
      display: inline-block;
      padding: 1em 2em;
      @include my-web-font();
    }
    
    [...]
    
    .page-title {
      font-size: 3rem;
      line-height: 1.4;
      @include my-web-font();
    }
    
    [...]
    
      .user-profile__title {
        font-size: 1.2rem;
        line-height: 1.5;
        @include my-web-font();
      }
    

    This is clearer for your code to write, but will actually compile as duplicated lines. So my answer below still makes sense.


    IMHO, I disagree with @Kareem Dabbeet's answer.

    I'm no BEM expert, but if you want to follow the exact convention, your bold text should stay a modifier of the element it is tied to. So you should get something like

    .block__element--bold {
      font-weight: bold;
    }
    
    .otherBLock__element--bold {
      font-weight: bold;
    }
    

    Even though, I myself use a lot of reusable classes, the convention says to organize your code according to your blocks/elements structure. There is no mention of some global utilities classes.

    However, you're right, depending on the use case, it can lead to code duplication. But BEM is all about some sort of separation of concerns. You should read and write your css focusing only on the block/element it is tied and not looking elsewhere. So it makes sense.

    Using classes that are not tied to any block or element alongside BEM will likely risk you to create conflicts in the long run.