Modular CSS with LESS
I’m starting a modular direction for LESS at my current gig, and I’d like to appeal to the masses on how they are structuring, and naming, for modular scalability.
My LESS Structure
.module {
// Module Styles
&--module-element {
// Element Styles
}
}
The “parent selectors” operator, or ampersand with a modifier compiles to:
.module-name {
// Module Styles
}
.module-name--module-element {
// Element Styles
}
Benefits
This gives us the benefit of nesting our LESS, therefore keeping things modular on the pre-compiled side of the fence. Once the code is compiled, however, we are given specific classes, rather than nested ones. This removes parent selector/class dependencies, and makes our code more scalable and reusable. We aren’t relying on a defined HTML structure, as we are with normal class nesting.
Secondly, this helps with CSS performance over traditional class nesting. Google tells us a bit about why:
Descendant selectors are inefficient because, for each element that matches the key, the browser must also traverse up the DOM tree.
^^ There’s more info in the link, but by limiting our nesting depth, we keep the browser from checking more nodes up the DOM tree. It’s a small performance win, but a win nonetheless.
Naming
This is where I’m still a bit up in the air. As you can see above, I’m using the class syntax of .module-name–module-element. This delineates the main module from any sub elements by two dashes. Further elements or modifiers down the tree are delineated by a dash. This gives other developers visibility into the reasons for our class naming, but is it enough?
I’ve been researching into BEM syntax; there is merit in defining sub elements vs modifiers. It’s a bit ugly and long-hand, but that’s not a reason to dismiss it.
Regardless, I’ll still use object-oriented layout classes for common use cases such as hiding an element. Those will live in their own LESS module. BEM(ish) syntax doesn’t work for everything.
What are your thoughts? What CSS organization/naming scheme do you have in place, if any? Is anyone out there using BEM, or a similar methodology?
Leave a Reply