Write less LessSeptember 5, 2011
I’ve written about using LESS before, touting the benefits of accelerating development and simplifying CSS. It seems the more I use it, the more awesome things I have to say about it. It adds many great features to regular CSS like variables, mixins, and nesting, but it’s the latter that that I want to talk about more today.
While I’ve written about using nesting in LESS before, turns out it can encourage good and bad practices as a web developer. Nesting is great, but not if you’re just adding bloat to your code. Take for instance this snippet of LESS:
When compiled, it looks like this:
So, what’s the problem? Looks fine at first, right? Well, not so much. You can actually improve this quite a lot by simplifying the nesting, thereby decreasing the amount of code, rendering time, file size, and most importantly specificity. With CSS, I’ve found you need to strike a balance between writing very generic code and writing very durable and modular code. Specificity as a result of nesting has a direct impact on both of those things.
Taking that same LESS code from above and rewriting it to not use unecessary parents in our selectors shows how we can attempt to get closer to achieving that balance.
Of course it depends on your markup and your needs, but this is the gist of what I’m getting at. Ultimately this isn’t a LESS-specific problem; anyone coding CSS can run into this, but with LESS it becomes easier to do unintentionally.
Don’t nest just to nest. Nest to simplify your final, compiled CSS. You’ll save code and headaches later on.