Appropriate use of BEM in CSS

2019-06-01 01:52发布

I'm an old hand with CSS, but have recently decided to take the plunge and begin using BEM. For the most part, I understand the value of using such a flat system, avoiding overly specific selectors etc...

My question is, is the following approach correct. It works, technically, but also seems fragile:

.badge {
  /* additional declarations */
  background: rgba(0, 0, 0, 0.2);
}
.badge--error {
  background: red;
}
.badge--success {
  background: green;
}

This works fine, because of the cascading nature of CSS. So the default background is overwritten by the modifier successfully. But if I put the modifier before the initial declaration, the modifier is ignored (because of the equal specificity).

Are there any issues with writing BEM this way? Is it considered bad practice to declare a default value of something like a background within the block, if it's to be overwritten with modifiers? Should the default background in this instance, live in a .badge--default modifier? Or have I written this in a true BEM fashion, and BEM actually relies on CSS' cascading in order to remain flat?

标签: css bem
1条回答
▲ chillily
2楼-- · 2019-06-01 02:53

You could make use of CSS variables

.badge {
  background: var(--background);
}

.badge--error {
  --background: var(--error);
}

.badge--success {
  --background: var(--success);
}


:root {
  --background: yellow;
  --error: red;
  --success: green;
}
<div class="badge">
  a badge
</div>

<div class="badge badge--success">
  a badge success
</div>

<div class="badge badge--error">
  a badge error
</div>

<div class="badge" style="--background: purple">
  a badge random
</div>

I don't see why a modifier could not modify just a background if it is(n't) set in the initial element.

For BEM I can recommend using a CSS preprocessor like SASS since it make it quite easy to nest elements there is less change of declaring some modifier before the initial declaration. Because of the nesting your CSS becomes much more organised. It is also easier to import different components so each component can live in its own file.

With SASS you can do:

.badge {
  &--error {}
  &--success {}
}
查看更多
登录 后发表回答