Specifying Styles for Child Elements of a BEM Modifier

I have the following BSS BEM style to define a simple window:

.box { /*styles */ } .box__heading {/*styles */} .box__image { /*styles */} 

I also need to show the window in error mode, so I defined the following modifier:

 .box--error {/*styles */} 

The problem I ran into is finding a good way to define styles for nested elements like box__heading when the field is in error mode.

I also define modifiers for both the header and the parent:

  <div class="box box--error"> <h2 class="box__heading box__heading--error"></h2> </div> 

or am I just doing this in css:

 .box--error {} .box--error .box__heading { /* error styles*/ } 
+5
source share
2 answers

Two ways are acceptable.

With modifier on element:

 .box__heading--error { } 

or with cascade:

 .box--error .box__heading { } 

However, if your block can be nested inside itself (recursively), you need to avoid the cascade. For instance:

 <div class="box box--error"> <h2 class="box__heading box__heading--error">Box 1</h2> <div class="box"> <h2 class="box__heading">Box 2</h2> </div> </div> 

You cannot use a cascade here because .box--error .box__heading will style field 2.

+5
source

For best practice, just use the box--error modifier in the mailbox container. When you are dealing with more complex modules, you do not want to add a modifier class to the whole element that needs styles according to the modifier.

In the Tarh example, there are two box__heading classes. This will cause a problem if the styles should not remain different, they simply should not have the same class name.

+2
source

Source: https://habr.com/ru/post/1232697/


All Articles