Appropriate use of BEM in CSS

心已入冬 提交于 2019-12-23 03:57:28

问题


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?


回答1:


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 {}
}


来源:https://stackoverflow.com/questions/52135505/appropriate-use-of-bem-in-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!