Picking up from where we left, let’s talk about LESS operations and structure in the 3rd and final part of our LESS tutorial (for the first 2 parts check here and here).

3. Operations

Variables specify things like colors and font-size but what about relative elements (like the text that’s a little bit lighter, or a paragraph’s font-size that’s a few pixels higher than the title font size)?

In such cases, we can take advantage of the fact that, with LESS, you can perform mathematical operations on existing values.

For example, we can make colors lighter or darker as shown below, and when we change the value that these operations depend on, they update accordingly.

This gives the .cloudmini element a margin of 10 pixels.

In the next table, we can see more details about the operators and functions you can use in LESS:

We can also set a variable to store the font size for level 1 headings, then compute the sizes for the other headings based on the level 1 value:

Here’s another example setting a dark blue base colour value for level 1 headings, then computing progressively lighter shades of blue for the other heading levels:

4.Cleaner Structure With Nesting

With CSS, we write out every rule set separately, which often leads to long selectors that repeat the same stuff over and over.

For example:

This syntax is fine when you have to deal with very simple classes but if you have a bigger chain with the same styles, then it’s not so easy to control your classes hierarchy. LESS allows us to nest rulesets inside other rulesets, as a way to show hierarchy. Let’s rewrite the example.

There is also a super easy way to use pseudo-classes (like :hover). The & symbol tells LESS not to put a space between the selector’s parent and the selector in the final CSS.

Check the cloud example with css and LESS:

Now you don’t have to repeat selectors over and over again!



The LESS compiler converts the nested version to regular CSS code.

Not only is the nested version more clear that way, but it’s easier to see the cascade.



Miscellaneous

A couple more things:

a) you can use two slashes // for single-line comments.

b) you can import other LESS files, just as in CSS, with @import:

That’s all folks!!!!

I hope you’ve found the LESS tutorials useful!

Ι’ve put all the above examples in github and have also created a banner with pure CSS only.

You can find it here.

Feel free to make changes and to send me your comments @Maria_Nas on twitter!







