How to style buttons using BEM?

285 views Asked by At

I'm new to html/css and I'm learning the BEM css methodology but I got stuck pretty early.

What I wanted to do:

  • have a button block
  • have a color modifier (default/primaryColor)
  • have different button styles (default/outline)

Based on what I understood about BEM I should define these classes:

.button {
    border: unset;
    padding: 4px 10px 4px 10px;
}

.button--primary {
    background-color: blue;
    color: white;
}

.button--outline {
    background-color: transparent;
    border: 1px solid black;
}

Everything works fine when I'm only using one of the modifiers. But when I have both instead of a blue border + blue textcolor I get black border + white textcolor.

Of course I could write something like this:

.primary {
    background-color: blue;
    border-color: blue;
    color: white;
}

.outline {
    background-color: transparent;
    border: 1px solid black;
}

.primary.outline {
    border-color: blue;
    color: blue;
}

But according to the BEM I should avoid these kind of selectors.

How should I resolve this problem? All I can think of is using local css variables but in a more complex scenario that would mean that I have to use a variable for almost every property I use and it just feels wrong.

HTML

<h1>using BEM</h1>
<button class="button">default</button>
<button class="button button--primary">primary</button>
<button class="button button--outline">outline</button>
<button class="button button--primary button--outline">primary outline</button>

<h1>not using BEM</h1>
<button class="button">default</button>
<button class="button primary">primary</button>
<button class="button outline">outline</button>
<button class="button primary outline">primary outline</button>

enter image description here

1

There are 1 answers

0
mwl On

I would go for:

<button class="button button--primary-outline">primary outline</button>

.button--primary-outline {
  border-color: blue;
  color: blue;
}