LESS File Structure
Since I’ve begun using LESS, my LESS file structure has remained relatively unaltered.
- Main stylesheet, containing most styles and importing other stylesheets
- Reset containing a modified version of the resets of Eric Meyer & the HTML5 Boilerplate
- List of variables, including image paths, colors, and the like that’ll be used several times throughout other stylesheets
- List of reusable components & CSS3 styles requiring browser prefixes
- Other various helpers that don’t change project to project
I plan to go more into the specifics of my organization and the contents therein in a future post, but I bring it up now to explain my current strategy of dealing with CSS variables.
Instead of muddying my
variables.less with every variable I create throughout a project, I’ve begun keeping only ‘global’ variables in that file and defining one-off variables inline with their relevant style declarations.
This makes it easy if I need to absolutely position something within
item, and want to retain the look of the element being padded.
Now obviously if I were to ever increase the
item-icon would still be positioned correctly.
I think this works pretty well for one-off variables, but I’d love to see LESS/SASS take this a bit further and allow truly ‘local’ variables: variables that need not be explicitly defined and only exist in the scope of a single style declaration. Might sound confusing, but it’s rather simple.
Let’s say you want to vertically center
item. One way to make that happen would be:
This should be a familiar technique to most, which relys on a negative top
margin of half the
height. And as a result, it’s largely inflexible; if the
height changes, the top
margin needs to as well. ‘Local’ variables could solve this.
Using ‘Local’ Variables in LESS/SASS
Now, as soon as
height is set, it exists within that scope as an accessible variable. With that variable, it’s just a matter of negating the value divided by two.
Height changes? No problem, the top margin adjusts as need be. Already have a ‘global’ variable of @height? Shouldn’t matter, as my suggested syntax is different. Wanting to use the same attribute value variable in many different declarations? Again, shouldn’t be an issue because each ‘local’ variable only exists within the scope of it’s own declaration.
I realize I’m very likely oversimplifiying, but I feel like this is something that could be parsed and work, and I know I’ve found myself wishing such a feature existed time and time again. Do you see value in this? Have a different workflow that solves this problem for you? Drop a comment, I’d love to hear about it and get some discussion going.