Greetings PageLines Enthusiasts, today's topic for discussion is LESS Variables.
I am sure we have all add that one client who just could not make his mind up on whether he/she wanted red or blue for their primary color. Or even worse call you up months later wanting to change colors and gradients. Even when faced with a fee they insisted on making colors and font changes.
So what are LESS variables?
Variables in LESS begin with the @ sign. What follows that can be any combination of letters and numbers, dashes and underscores. Once the variable has been named, follow with a colon (similar to CSS) and define the variable. This can include a hex code for a color (very common) or a string enclosed in quotes. LESS takes away some of the repetitiveness that comes with writing CSS. The variables will allow you to store a constant value that later can be reused in the entire stylesheet.
Here are some examples writing with LESS variables versus the traditional CSS way.
Traditional CSS:
.class1 { background-color: #2d5e8b; } .class2 { background-color: #fff; color: #2d5e8b; } .class3 { border: 1px solid #2d5e8b; }
Writing with LESS:
@color-base: #2d5e8b; .class1 { background-color: @color-base; } .class2 { background-color: #fff; color: @color-base; } .class3 { border: 1px solid @color-base; }
AS you can see in the examples that writing with LESS is pretty easy. To compare the two methods the developer writing with traditional CSS will have to change all the hex code in his style sheet one by one to change the color. The developer writing with LESS just needs to change the hex code in his variable and the color will change for the entire site where ever he has the variable placed.
And you can use LESS variables for more than just color. Also note that you can name them what ever you like as long as they have the @ in front of it.
@blue: #00214D; @red: #CF142B; @white: #FFF; @black: #000; @baseFontSize: 15px; @baseLineHeight: 22px;
So what is the benefit of using LESS variables.
Once you start to use variables in your projects you will find that changing colors and font sizes will be easier. Instead of going through the entire stylesheet changing every hex code all you would need to do is change the value of the variable and it will change everywhere.
I found it very useful when testing out various color schemes so the client to see how the site would look with certain primary and accent colors. If you find some other uses for LESS variables feel free to post them in the comments.
How can I use LESS Variables in an external CSS?