Search code examples
cssmethodologybem

How override modifiers in nested rules


I have a question concerning BEM specificity. I want to be sure to use that methodology in the best way possible. Lets say I have generic style for a headline applying a color. Then my parent container has a modifier that edit the background. I then need to override any subsequent color rules applied to that headline in order to prevent contrasts problems but also probably a whole set of other elements.

How do I extrapolate this issue to much more complex situations? I know I could only override all the styles manually but is there a better way to handle it in the BEM methodology? Is that even an issue?

CSS

.headline{ 
    ...
    color:#513252; 
    ...
}
.section--bg-purple{ 
    background-color:#513252;
}

HTML

<section class="section section--bg-purple">
    <h1 class="headline headline--main">Lorem ipsum</h1>
</section>

I somehow did something like that in my LESS, but I am not sure if there is a better way:

.section{
    ...
    &--bg-purple{
        background-color:@c_purple;
        [class^="headline"]{
            color:#ffffff;
        }
    }
    ...
}

Solution

  • I would prefer to use mixin .section__headline here.

    html:

    <section class="section section--bg-purple">
        <h1 class="section__headline headline headline--main">Lorem ipsum</h1>
    </section>
    

    css:

    .headline{ 
    
        ...
        color:#513252; 
        ...
    }
    
    .section{
        ...
        &--bg-purple{
            background-color:@c_purple;
            // here it is
            .section__headline {
                color:#ffffff;
            }
        }
        ...
    }