- Webknit
- WON
- Base
Harry Roberts wrote a nice little article about specificity in CSS and how you can try to avoid it. One point in particular stood out for me.
“Do not nest selectors unnecessarily. If .header-nav {} will work, never use .header .header-nav {}; to do so will literally double the specificity of the selector without any benefit.”
I have always nested my SASS like this
#### HTML #### <div class="header"> <div class="header__nav"> </div><!-- .header__nav --> </div><!-- .header --> #### CSS #### .header { width: 100%; .header__nav { width: 50%; } }
Once compiled the CSS for .header__nav is:-
.header .header__nav {width: 50%}
As soon as I read Harry’s post I realised that there is absolutely no need whatsoever for the .header class to come before the .header__nav. Not only is it over specific but it’s making the CSS file larger – and therefore slower – than it needs to be. I wouldn’t write this in Vanilla CSS so no need to have it in my SASS. The following code is better.
.header { width: 100%; } .header__nav { width: 50%; }
The nesting in SASS made my code easier to debug and read but Harry also recommended a practice that could help solve that issue.
.header { width: 100%; } .header__nav { width: 50%; } .section { color: red; }
By indenting it visually show the relationships making things much easier to read. I must admit I quite like this approach and I’m going to try it out on future projects.
I think the main rule is “Don’t nest an element unless it needs to be nested”. For example I can’t take that h2 out of the .header__nav as it’s specific to that element. If I were to move it outside it’s going to apply it to every h2.
.header__nav { width: 50%; h2 { color: red; &:hover { colour: blue; } } }
Obviously this is a very simple example but hopefully you can potentially understand what needs to be inside and what can be outside of the “nest”.
I’m sure that some problems are going to arise and I will spend hours pondering how my SASS should be structured. However I can see the benefit of adopting this new approach and I’m going to merge it into my SASS workflow as of today.
Thanks for reading.
EDIT
tweeted with a very good suppestion
There’s another way! You don’t have to lose your nice indenting—have it both ways
.header { width: 100%; &__nav { width: 50%; } } Outputs .header {width: 100%}; .header__nav {width: 50%};
Perfect solution for BEM syntax.