css naming conventions

by Richard Hunter

HTML

<div class="broken-module">
     <h1 class="header">broken module</h1>
    <p>
        This is broken because the header is italicised even though
        we do not declare it to be so in our module's css.
    </p>

</div>
<div class="recovering-module">
     <h1 class="recovering-module__header">recovering module</h1>
    <p>The problem here is fixed but we are left with unwieldy class
        names in our html and css</p>
</div>
<div class="healthy-module">
     <h1 class="_header">healthy module</h1>
    <p>This is the optimum solution: The styles are correct
    and we have terse and readable class names in our code</p>
</div>
<p>

    
    A big problem that we encounter when working with CSS is name-clashes between selectors. If two style rules have the same selector names then declarations in first rule that are not overridden in the second rule will affect the element to which the rule applies. This is the way that CSS is supposed to work however if the use of the same selector is unintentional it can result in unexpected behaviour. One could simply override in the second rule all the unwanted declarations which exist in the first one, but this would be messy, and would not prevent the possibility of another developer adding new declarations to the first rule which would affect the second.
</p>


<p>
    Another approach to this problem is to create namespaces for declarations by nesting selectors. If for a module of CSS we create a 'root' selector such as '.my-module' and then nest all the rest of the modules selectors within this one then we create rules which are unique to this module and should not affect elements anywhere else on the page or site.
    
</p>

<p>
    This is only a partial solution however. Whilst style rules within our module cannot leak out, style rules from elsewhere in the CSS file can still leak IN to our module.
    
</p>



<p> An example will demonstrate the problem. We have a module called 'broken module' with a similarly...

SCSS

.header {
    font-style : italic;
}

.broken-module {  
    .header {   
        color : red;     
    }
}

.recovering-module {
    .recovering-module__header {  
        color : blue;     
    }  
}

.healthy-module {
    ._header { 
        color : green;
    }
}