Search code examples
htmlcsssvgsassbem

CSS BEM - Class for SVG


I'm trying to useBEM style for my SASS/CSS files. Everything works fine, but I have problems styling SVG files.

BEM says that there should be no tag or ID selector, only class selectors. However, I want to give my SVGs different colors and sometimes different widths and heights.

Currently I can only do this with a tag selector like this:

block__icon {
    height: 36px;
    width: 36px;

    svg {
      width: 100%;
      height: 100%;
      fill: #fff;
      fill-opacity: .8;
    }
}

HTML:

<div class="block__icon">
   <svg ...></svg>
</div>

Do you know a better way?


Solution

  • You can remove the div and style the svg directly. With the modifiers you can change the appearance of the svg like the color or size:

    <svg class="block__icon block__icon--large"></svg>
    

    I would structure the css for it like this:

    .block {
      &__icon {
        height: 36px;
        width: 36px;
        fill: #fff;
        fill-opacity: .8;
    
        &--color-blue {
          color: blue;
        }
    
        &--large {
          height: 72px;
          width: 72px;
        }
      }
    }