Learning LESS: Variables

let’s dive in to LESS Variables, and showcase some of what you can do with them.

THE SYNTAX

The syntax for LESS is almost identical to CSS. And the creators of LESS were very smart and made LESS completely compatible with CSS which means you can write CSS in your LESS files. It’s basically the best of both worlds! Just remember to write your LESS files names as .less and not .css.

VARIABLES

Variables in LESS begin with the @ sign. What follows that can be any combination of letters and numbers, dashes and underscores. Once you’ve named your variable, 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. Let’s take a look at a few variables and see how they’ll render once they’re compiled.

@blue: #00214D; @red: #CF142B; @white: #FFF; @black: #000; @baseFontSize: 15px; @baseLineHeight: 22px;

Pretty simple, right? Now you can use those variables in any of your other LESS files throughout your project where you would use the hex code. This is a fantastic way to keep your code clean and easy to manage. For example, I like to set up a single LESS file that is just my variables, which includes font sizes, colors, headers, etc.

When you use your variables in your LESS files, they compile to be perfectly clean CSS. Let’s take a look.

h1 { color: @red; } h2 { color: @blue; } h3 { color: @black; } p { color: @black; font-size: @baseFontSize; line-height: @baseLineHeight; }

Which compiles to…

h1 { color: #CF142B; } h2 { color: #00214D; } h3 { color: #000; } p { color: #000; font-size: 15px; line-height: 22px; }

SETTING STRINGS AS VARIABLES

Variables don’t have to be just colors or font sizes. We can also set strings to variables, just like you would in JavaScript or PHP. This can become extremely valuable when using Icon Fonts in your web design, as it’s best practice to set Icon Fonts with pseudo elements to maintain accessibility instead of just typing characters in a specific class element. Let’s take a look at variables as strings.

@name: "Alex Ball"; @description: "I love to write and code."; a:before { content: @description; }

When the code above is compiled, we get this.

a:before { content: "I love to write and code."; }

WRAPING UP VARIABLES

That concludes our discussion on variables in LESS, and while it was a shorter lesson, it’s extremely valuable and worth practicing some on your own. As I mentioned in the Introduction, go out and download LESS.app and try out using variables in your projects. You’ll be amazed at how quickly it can speed up development time and maintainability.

In the next segment of Learning LESS, we’ll dive in to Mixins, one of the most powerful advances in LESS.

Have questions on variables and how they work in LESS? Or having trouble getting your LESS files to compile correctly? Comment below and I’ll get to them as soon as possible!

See you next time.