SASS + BEM is pretty much like the sky most of the time, but my common struggle is understanding how best to define BEM modifiers for an element that affects its children when using SASS parent selectors.
I have the following component defined in SASS using BEM style syntax:
.card { background-color:
This works well due to the SASS parent selector. It keeps the relevant code organized and autonomous.
But when I need to add a modifier that modifies the child using the parent selector, the idea quickly falls apart:
.card { padding: 2em; &__value { font-size: 1.5em; color:
Nope. It generates this:
.card { padding: 2em; } .card__value { font-size: 1.5em; color:
It would be wiser to somehow get this selector:
.card--big .card__value { font-size: 3em; }
The reason for this is that you can simply add a modifier to the top-level element and affect any or all of the child elements.
I tried a couple of approaches:
Use two structures
.card { padding: 2em; &__value { font-size: 1.5em; color:
This works (especially in this simplified demo), but in a more complex set of components with many modifiers, this can be a potential pain for maintaining and saving errors. In addition, it would be nice to continue using the SASS parent selectors, if possible.
Use a variable for an element
.card { $component: &;
It works well. But it seems silly to define an element as a variable. Maybe this is the only real way to do this ... I'm not sure. Are there more efficient ways to structure this?
html css sass bem
Jake wilson
source share