Appropriate use of BEM in CSS

两盒软妹~` 提交于 2019-12-06 16:13:04

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