What is LESS and how to use it. LESS (style language)

a less apocalyptic view of the future

not so pessimistic views about the future

A fair heritage is no less agreeable than a fair wife.

A nice inheritance is no less pleasant than a pretty wife. ☰

Traffic is one of the less agreeable aspects of city life.

Traffic jams are one of the least pleasant aspects of city life. ☰

The outline became less and less distinct as the light faded.

The outlines became less and less clear, while the light gradually faded. ☰

The community is demanding a less aggressive style of policing.

The community is demanding a less aggressive style of law enforcement. ☰

Eat less and exercise more if you want to live to a ripe old age.

Eat less and exercise more if you want to live to a ripe old age. ☰

The back view of the hotel was even less appealing than the front.

From the back this hotel looked even less attractive than from the front. ☰

No less a luminary than Wilhelm Furtwangler conducted the premiere.

The conductor at the premiere was none other than the celebrity Wilhelm Furtwängler himself. ☰

The system is failing most disastrously among less academic children.

This system is absolutely unsuitable for children who are not inclined to study. ☰

"Will you please come with me?" It was less a request than a command.

Come with me, please. - It was not so much a request as an order. ☰

As the years went by, he seemed to care less and less about his reputation.

Over time, it began to seem that he cared less and less about his own reputation. ☰

The premiere was attended by no less a personage than the president himself.

The premiere was even attended by not just anyone, but the president himself, in person. ☰

People who can exercise some control over their surroundings feel less anxious.

A person who can exercise some control over their environment feels less anxious. ☰

Outgoing people are more high-spirited and less anxious about social situations.

Sociable people are more cheerful and less concerned about social problems. ☰

When she lost her looks (=became less attractive) she found it difficult to get work.

As she lost her looks (i.e., became less attractive), she found it very difficult to get a job. ☰

Polls show that voters are growing less and less content with the current administration.

Polls show that voters are increasingly dissatisfied with the current administration. ☰

I couldn't care less about her. *

I could care less about what you believe. *

I don't give a damn what you think. ☰

Lesser Wain

Less of your sauce, my girl!

Less insolence, my girl! ☰

Of two evils choose the less.

Of two evils choose the less. (last) ☰

All meat is sold less the bone.

All meat is sold without bones. ☰

She walks less than she should.

She walks less than she should.

If we consider preprocessors together with CSS, we get a clearer picture than considering the concept of a preprocessor separately.

Definition

CSS preprocessor (from the English CSS preprocessor) is an add-on to CSS that adds previously unavailable capabilities to CSS using new syntactic constructs.

The main task of the preprocessor is to provide convenient syntactic structures for the developer to simplify, and thereby speed up the development and support of styles in projects.

CSS preprocessors convert code written using a preprocessor language into clean and valid CSS code.

With preprocessors, you can write code that targets:

  • Human readability
  • Structured and logical
  • Performance

And this is only a small part of what the preprocessor can give you. But don't get ahead of yourself.

Syntactic sugar

Before we look further at CSS preprocessors, let's update our vocabulary with a new concept: syntactic sugar.

Syntactic sugar (from the English syntactic sugar) are additions to the syntax of a programming language that do not introduce any significant changes or new features, but make the language more readable for humans.

Syntactic sugar introduces into the language alternative options records of constructions embedded in this language. By alternative recording options we mean shorter or more convenient constructions for humans, which will ultimately be converted by the preprocessor into the source language, without syntactic sugar.

If we try to apply this concept to CSS preprocessors, then it general case, fully describes their essence. Let me remind you once again that the main task of preprocessors is to simplify and speed up development, but how else can this be done if you do not introduce alternative recording options?

What types of CSS preprocessors are there?

It's time to move on to more specific examples, namely to the CSS preprocessors themselves. At the time of writing, there are three popular preprocessors:

  • Sass (SCSS)
  • Stylus

And a few minor players for us:

  • Closure Stylesheets
  • CSS Crush

We will talk about the first three separately a little lower, but we won’t talk about the last two at all, due to their unpopularity. If desired, descriptions of these preprocessors can be easily found in a search engine.

What's the point of using preprocessors?

As I noted above, the main advantages are code readability, structuring and increased productivity.

There are also other reasons to start using a preprocessor today. I want to draw attention to this, since developers in the past, and many even now, refuse to use preprocessors, finding them complex, incomprehensible and unnecessary.

CSS is hard

Standard CSS is difficult. The non-nesting syntax that CSS preprocessors offer is simply hard to read. In addition, you need to remember the parent name when nesting. The lack of normal variables and "functions" makes CSS code messy and narrow-minded.

Available documentation

Gone are the days when documentation from preprocessors was available only to people “in the know.” Now anyone can as soon as possible master any of the preprocessors, and with minimal costs strength

Ease of use

Using preprocessors is easier than before, and much easier. To do this, you just need to install a program that will monitor the files intended for the preprocessor, and when they change, will compile the contents of these files into pure CSS code.

For more advanced users there are special project builders. Don't think that just because you're using a preprocessor program rather than a project builder that you're not cool enough. In fact, such faucets offer full control and advanced settings, but do not make you a Jedi.

Code structure and consistency

The most popular feature offered by any CSS preprocessor is the ability to nest selectors within each other. I won’t give an example now, since the corresponding part of the book will be written about the capabilities of Less, including nesting. At this point, all you need to know is that when using preprocessors, you can nest one selector within another, and another within a third, resulting in something similar to the table of contents of a book:

1. Parent selector 1.1. Nested selector 1.2. Nested selector 1.2.1. Nested selector 1.3. Nested selector

Of course, in real life selectors cannot begin with numbers, however, to draw a parallel between nesting and table of contents, I think such an omission is appropriate here.

Impurities

To put it very briefly, using mixins (from the English Mixins), you can make the code reusable. This helps to avoid helper classes in the markup or duplication of properties from selector to selector.

Modularity

Another bonus that would persuade me to start using a CSS preprocessor right now would be the ability to nest files within files, that is, in other words, to concatenate files in a given sequence. Yes, this can be done using pure CSS, but coupled with other features it turns out to be a very powerful tool.

At the same time, we get the opportunity to share modules (mixin libraries) that we created for our needs and found useful for other people. It turns out that any developer can download your library and use it for their own purposes, calling the mixins you wrote as needed.

Why not wait for CSS to evolve?

The development of CSS is taking very small and uncertain steps, as the W3C prioritizes the speed of CSS response (performance). On the one hand, this is correct and very important, but on the other hand, it is a lack of convenience for developers.

As an example, I’ll use one of the CSS4 specifications, which was introduced under pressure from developers - the parent selector. Such a long path from the idea to the decision was due to the fact that the W3C considered such a selector to be slow and its further use on sites would lead to wild slowdowns. Of course, we are talking about the widespread use of this selector, and not about isolated cases.

So don’t expect revolutions and changes in the near future that could overshadow the functionality and capabilities of CSS preprocessors.

Types of preprocessors

Of course, as in any other area, there is always competition, and in the preprocessor market there are now three main, warring camps:

  • Sass (SCSS)
  • Stylus

I call them hostile, because each adherent of one of the preprocessors considers it his duty to throw impurities at representatives of other, let’s say, faiths. This hostility is especially common among fans of the Sass preprocessor, which is considered the oldest and most powerful of all three preprocessors.

For the sake of completeness, I want to give a brief overview of each preprocessor:

Less

Actually, the hero of this book. The most popular preprocessor at the time of writing. Founded in 2009 by Alexis Sellier and written in JavaScript (originally written in Ruby, but Alexis made the right move at the right time). Has everything basic capabilities preprocessors and even more, but does not have conditional structures and loops in the usual sense for us. The main advantage is its simplicity, almost standard for CSS syntax and the ability to expand functionality through a plugin system.

Sass (SCSS)

The most powerful of the CSS preprocessors. Has a fairly large developer community. Founded in 2007 as a module for HAML and written in Ruby (there is a port to C++). It has a much larger range of capabilities compared to Less. The capabilities of the preprocessor itself are expanded by the multifunctional Compass library, which allows you to go beyond CSS framework and work, for example, with sprites in automatic mode.

Has two syntaxes:

  • Sass (Syntactically Awesome Style Sheets) is a simplified CSS syntax that is identity-based. Considered obsolete.
  • SCSS (Sassy CSS) - based on standard CSS syntax.
Stylus

The youngest, but at the same time the most promising CSS preprocessor. Founded in 2010 by a well-known personality in our circles, TJ Holowaychuk. They say this is the most convenient and extensible preprocessor, and it is also more flexible than Sass. Written in JavaScript. Supports a lot of syntax options from CSS-like to simplified (missing: , ; , () and some parentheses).

CSS - simple and accessible tool. However, it has its limitations, especially when it comes to maintaining the finished code. When you need to modify thousands of style lines spread across multiple files, the task becomes a challenge.

To overcome this problem, CSS preprocessors have been created that allow you to combine styles dynamically. There are several options (such as LESS and SASS), but in this lesson we'll look at LESS.

LESS Editor

At the time of writing this tutorial, there was only one editor entirely dedicated to working with LESS files - ChrunchApp. This application cross platform, built on Adobe Air, it can be run on Windows, Mac OSX and Linux.

For other editors (such as Dreamweaver, Coda, NotePad++ and SublimeText 2) there are plugins or add-ons that allow you to provide LESS syntax highlighting.

Using LESS

LESS is very easy to use. You just need to add two lines to head tag your HTML document. The first line contains the name of your .less file, and the second line contains the connection of the less.js library (it can be downloaded from the official website).

In our lesson we will show another way. We will use the LESS compiler: for Windows we can use WinLess, and for Mac OSX we can use LESS.app.

Create a .less file in the working directory. Then open the compiler (WinLESS or LESS.app) and import the working directory into it. the compiler will find all .less files. That's all. Now, whenever we change the .less file, the compiler will automatically generate regular CSS code into a .css file that is accepted by the browser.

All that remains is to tie CSS file to the HTML document:

LESS syntax

Unlike regular CSS, LESS is more like a programming language. It's dynamic, so it's logical to expect it to use variables, operations, and scope.

Variables

Let's look at the variables first.

When working with CSS, you've probably often encountered a situation where a repeating value is set in multiple blocks throughout a stylesheet.

Class1 ( background-color: #2d5e8b; ) .class2 ( background-color: #fff; color: #2d5e8b; ) .class3 ( border: 1px solid #2d5e8b; )

Everything is great until you have to sift through 1000 identical sections of code throughout the entire style sheet to change the value. This situation can arise when working on a large project.

When using the LESS preprocessor, this problem is easily solved using variables. Variables allow you to store values ​​that can be reused in a style sheet.

@color-base: #2d5e8b; .class1 ( background-color: @color-base; ) .class2 ( background-color: #fff; color: @color-base; ) .class3 ( border: 1px solid @color-base; )

In the example above, the @color-base variable stores the value #2d5e8b . And when you need to change the color, you will only need to change the value in the variable.

You can use other values ​​in the variable:

@font-family: Georgia @dot-border: dotted @transition: linear @opacity: 0.5

Admixtures

In LESS, you can use mixins to store a set of rules and apply them to other sets. For example:

Gradients ( background: #eaeaea; background: linear-gradient(top, #eaeaea, #cccccc); background: -o-linear-gradient(top, #eaeaea, #cccccc); background: -ms-linear-gradient(top , #eaeaea, #cccccc); background: -moz-linear-gradient(top, #eaeaea, #cccccc); background: -webkit-linear-gradient(top, #eaeaea, #cccccc);

In the above example, we are setting the gradient color in the .gradients class. Then when you need to add a gradient you just need to insert .gradients like this:

Box ( .gradients; border: 1px solid #555; border-radius: 3px; )

The .box class inherits all declarations from .gradients . Therefore, the above LESS expression is equivalent to the following regular CSS code:

Box ( background: #eaeaea; background: linear-gradient(top, #eaeaea, #cccccc); background: -o-linear-gradient(top, #eaeaea, #cccccc); background: -ms-linear-gradient(top , #eaeaea, #cccccc); background: -moz-linear-gradient(top, #eaeaea, #cccccc); background: -webkit-linear-gradient(top, #eaeaea, #cccccc); ; border-radius: 3px )

When working with CSS3, you can use the LESS ELements library to make your work easier. LESS Elements is a collection of common CSS3 mixins that are often used in styling, such as border-radius , gradients , drop-shadow and so on.

To use LESS you just need to add the @import rule to the LESS file. You just need to download the library and place it in your working directory.

@import "elements.less";

Now you can use all the classes from elements.less . For example, to add a border corner radius of 3px to div element, you need to write:

Div ( .rounded(3px); )

Nested rules

When working with regular CSS code, the following code structure is quite common:

Nav ( height: 40px; width: 100%; background: #455868; border-bottom: 2px solid #283744; ) nav li ( width: 600px; height: 40px; ) nav li a ( color: #fff; line-height : 40px; text-shadow: 1px 1px 0px #283744;

In regular CSS code, we select children by specifying a parent in each ruleset.

In LESS, you can improve on the above set of rules by nesting children within a parent element:

Nav ( height: 40px; width: 100%; background: #455868; border-bottom: 2px solid #283744; li ( width: 600px; height: 40px; a ( color: #fff; line-height: 40px; text- shadow: 1px 1px 0px #283744; ) ) )

You can also use pseudo-classes, for example:hover, using the ampersand character (&). Let's say we want to add :hover to the link tag:

A ( color: #fff; line-height: 40px; text-shadow: 1px 1px 0px #283744; &:hover ( background-color: #000; color: #fff; ) )

Operations

You can also use operations in LESS. Addition, subtraction, multiplication and division are available.

Let's say element B is twice as tall as element A:

@height: 100px .element-A ( height: @height; ) .element-B ( height: @height * 2; )

First we define the variable @height and assign it to indicate the height of element A.

In element B, we simply multiply the value of the variable by 2. Now, when we change the value of the @height variable, element B will always be twice as tall.

Area of ​​visibility

LESS uses the concept of scope. Variables from the local context are used first, and if they are not there, a search is made in the wider scope.

Header ( @color: black; background-color: @color; nav ( @color: blue; background-color: @color; a ( color: @color; ) ) )

In the example above, the header has a color variable set to black , but the nav element's background will be blue because the @color variable is in the local context.

Conclusion

In the next lessons in the series, we will look at an example of real-life use of LESS and some useful aspects of the toolkit.

In this article we will talk about the capabilities of the Less preprocessor, which, due to some unknown forces, almost no one uses. In addition, we’ll talk about the missing functionality and try to add it.

I suggest starting with a small reminder of what you shouldn’t do, even if you really want to. Take a look at the Alesya framework, which was developed by a friend who teaches Less to other people. Try to take a close look at the file ./core/functions.less . Although no, don’t follow the link, just look at the screenshot of a small part of this file. When I saw it for the first time, I was simply shocked.

The justification is that the cycles are very slow, as a result, the translation speed of Less in CSS decreases, and the translation time increases. Pentium 4? No offense, but it's frustrating.

I will give an excerpt from the book “HTML5 for Web Designers” authored by Jeremy Keith, who not long ago became the hero of public pages on VK:

Let's assume that there is an evil monster in the world who hates the Internet and all Internet users. This gentleman probably doesn’t care that embedding an audio file on a page that starts playing automatically is incredibly rude and stupid. Using the autoplay attribute, you can satisfy his deeply vicious desires.

If you ever use the autoplay attribute like this, know that I will find you.

Therefore, if you also use Less, know that they are already looking for you and will soon find you.

Selector Expansion

We have a flow breaker typical of our days:

Clearfix ( &:before, &:after ( content: " "; display: table; ) &:after ( clear: both; ) )

And some selector that implies the use of clearfix. Of course, you can use .clearfix as a mixin and produce it everywhere great amount unnecessary but necessary code. However, you can avoid this by using selector expansion.

For example, like this:

Navbar ( &:extend(.clearfix all); ... ) .navbar-collapse ( &:extend(.clearfix all); ... ) .ad ( &:extend(.clearfix all); ... )

As a result, our class.clearfix begins to communicate with friends from various parts your styles, without sharing extra lines of code with anyone:

Clearfix:before, .clearfix:after, .navbar:before, .navbar:after, .navbar-collapse:before, .navbar-collapse:after, .ad:before, .ad:after ( content: " "; display: table; ) .clearfix:after, .navbar:after, .navbar-collapse:after, .ad:after ( clear: both; )

Of course, you shouldn't abuse this. To be honest, I advise you to use the selector extension only for clearfix and in cases where the rule applies: “Well, it’s really necessary, I can’t do anything, otherwise it will be worse.” You should not use selector extensions when manipulations with element styles occur. The most common and stupid mistake:

Class ( color: #fff; background: #fff; ) .new-class ( &:extend(.class); ) // .class, // .new-class ( // color: #fff; // background: #fff; // )

You can't do that. This is silly. It's better to use .class as a mixin:

Class ( color: #fff; background: #fff; ) .new-class ( .class; ) // .class ( // color: #fff; // background: #fff; // ) // .new-class ( // color: #fff; // background: #fff; // )

Remember this!

Import Options

Please take a look at the documentation section "import directive options".

I will give only a brief description of the most important of these parameters:

reference

Allows you to use .less files, but not display their contents without an explicit call. A very useful option if you use Bootstrap as a library and not a framework, that is:

@import (reference) "bower_components/bootstrap/less/bootstrap"; .my-alert ( .alert; )

Using this parameter makes it possible to include files with no .less extension. The parameter is not required, since everything will work without it, but, nevertheless, if you like order, it will come in handy. This parameter can be used when connecting files with an extension other than .less, for example, .variables, .mixins.

You need to apply it like this:

@import (keyword) "filename";

WITH detailed description and examples can be found on the documentation pages. So, politely, I send you, my reader, to read the documentation. Unforgettable feelings:)

Conditionals

Less has conditionals. Yes, they are not full-fledged if you compare them with other preprocessors, but still their presence cannot but rejoice. They seem even more convenient to me than @if in Sass, although there is no practical difference.

Mixin(@variable) ( & when (@variable = 1) ( content: "TRUE" ) & when not (@variable = 1) ( content: "FALSE" ) .class-test ( .mixin(1); . mixin(2);

As a result, we will get the following CSS:

Class-test ( content: "TRUE"; content: "FALSE"; )

What just happened? Magic?

Not really. The when keyword here replaces the usual if in all programming languages ​​and has only two logical element: not - negation, and - simple and and that's it, there's nothing more. I can't do anything particularly cool with this, but I use conditional operator so that unnecessary code is not generated. One such situation, for example, is border-radius property in the button style generator. Why would any property be specified once again during generation if its value does not play a role (0)? - That's right, no need.

Interpolation of Variables

There is an interesting design in Less when we get the value of one variable depending on others.

// Variables @clr-grey-100: #fafafa; @clr-grey-200: #f5f5f5; @clr-red-100: #ffebee; @clr-red-200: #ffcdd2; .mixin(@color, @temperature: 500) ( color: ~"@(clr-@(color)-@(temperature))"; background: e("@(clr-@(color)-@(temperature) )"); ) .class-test ( .mixin(grey, 100); &-test ( .mixin(red, 200); ) )

This example calls a mixin whose parameters are color ( @color) and its temperature ( @temperature). Next, we collect all the variables into one, that is, simply put, we construct a new variable and get its value. The process when a string, relatively speaking, turns into a call to a variable is interpolation of variables.

Note that in this example we use curly braces after the dog - this is very important.

At the exit:

Class-test ( color: #fafafa; background: #fafafa; ) .class-test-test ( color: #ffcdd2; background: #ffcdd2; )

By the way, I couldn’t find this in Sass and Stylus. Maybe an attentive reader can tell me? :)

Cycles

Many adherents Sass preprocessors and Stylus insist that Less has no loops, but there are some, although not the same as everyone else’s. It's just inconvenient to use them.

Let's say we have a list of colors:

@list-red: #ffebee, #ffcdd2, #ef9a9a, #e57373, #ef5350, #f44336, #e53935, #d32f2f, #c62828, #b71c1c;

For example, let's create a class for each color:

Color-generator(@index: 1, @color) when (@index Click “+” at the bottom of the window and select the file type to track less. On this moment, if everything was done correctly, then even with default settings our IDE will monitor less files in the project and compile them in real time when they change and place them in a folder next to the compiled source file. The main thing is to make sure that in the Program field the path to the less compiler (which we installed in the console) is specified.

Working with LESS

Finally, let's have some fun and start writing LESS code. As you will see, the code is easy to read and understand, since the syntax is very similar to regular css, which reduces the barrier to entry for a developer to use it.

Variables in LESS work the same way as in PHP, JS and most other programming languages. You can use them to store a value, and then use variables instead of the value itself whenever you need it.

@header-font: Georgia ; h1 , h2 , h3 , h4 ( font-family : @header-font; ) .large ( font-family :@header-font; )

In the example above, we declare the variable @header-font and write the value “Georgia” to it. Now we can use this variable whenever we want to install the Georgia font. If we decide that Trebuchet MS is better suited for our headers, then we will not need to look through the entire file, we will simply change the value of the variable.
I've found a great use for variables in defining site colors. In the good old days (which weren't that long ago) I used something like this:

/* Colors for my Website #ff9900 - Orange - used for links and highlighted items #cccccc - Light Gray - used for borders #333333 - Dark Black - Used for dark backgrounds and heading text color #454545 - Mid Black - Used for general text color */ body ( background : #333333 ; color : #454545 ; ) a ( color : #ff9900 ; ) color : #333333 ; )

There's nothing wrong with documenting your colors like this, it's good practice, the problem is that the documentation has nothing to do with the functionality of your styles. If you decide to change colors after line 2000 of code and then change your mind at line 3567, it will be extremely difficult to correct all the colors and documentation.
With LESS we can modify and document our workflow at the same time.

/* Colors for my Website */ @color-orange: #ff9900 ; @color-gray_light: #cccccc ; @color-black_dark: #333333 ; @color-black_medium: #454545 ; body ( background : @color-black_dark; color : @color-black_medium; ) a ( color :@color-orange; ) h1 , h2 , h3 , h4 , h5 , h6 ( color : @color-black_dark; ) Variable scope

The scope of variables describes the places where they are accessible. If you define a variable at the very beginning of the LESS file, then it will be available to any code written after it.
You can also define a variable inside a CSS rule. In this case, the variables will not be accessible outside of this rule; they can be used locally.

a ( @color : #ff9900 ; color :@color; ) button ( background : @color; )

In this example, LESS will not be converted due to the error @color is not defined for use inside a button element. If a variable is declared outside an element and inside another element, then it will only be accessible locally.

@color: #222222 ; a ( @color : #ffffff ; color :@color; ) button ( background : @color; ) Variables within variables

If you've coded in PHP, then you know that you can declare a variable name in another variable.

@color-chirstmas_red: #941 f1f ; @name-of-color: "color-chirstmas_red" ; color : @@name-of-color ;

Personally, I don't use this much since variables within variables are almost useless without closures, but I'm sure there will be clever examples of using this.

Constants and Variables

It's important to note that, contrary to what you just read, variables in LESS are more like constants. This means that they, unlike variables, can only be defined once.

Operations

You can achieve incredibly precise control using operations in LESS. The idea is simple:

.button ( @unit : 3 px; border :@unit solid #ddd ; padding : @unit * 3 ; margin : @unit * 2 ; )

The code above sets the @unit variable to 3px. We then set this value to the border width, the padding to three times this width, and the margin to twice this width.
You can use multiplication, division, addition and subtraction operations. To create a block with a border that increases the width of the sides clockwise, you can use the following code:

.box ( @base_unit : 1 px; border : @base_unit @base_unit + 1 @base_unit + 2 @base_unit + 3 ) Color management

My favorite feature of LESS is the color management. You can use operations to mix colors and several special functions for working with color.

Color Operations

If you want to change the value of a color, you can do so by subtracting or adding another color.

@color: #941 f1f ; button ( background : #941f1f + #222222 ; border : #941f1f - #111111 ; )

The above background operation will increase each HEX value by 2. The result will be “B64141” - a lighter version of the original color. The frame operation will reduce each HEX value by 1 and produce more dark color: “830E0E”.
In practice, there are many cases when we start with base color and we need a slightly darkened or lightened version of it.

@color-button: #d24444 ; input .submit ( color :#fff ; background :@color-button; border :1 px solid @color-button - #222 ; padding :5 px 12 px; ) Color functions

There are many more possibilities for working with color; LESS allows you to manipulate them on link level. You can lighten, darken, saturate, desaturate, and rotate colors. Take a look at the following examples with pictures to understand what each one does.

@color: #3 d82d1 ; .left_box ( background :lighten(@color, 20%) ; ) .right_box ( background :darken(@color, 20%) ; ) Nesting

When writing CSS, we use cascading styles. To change the margins of a paragraph only inside an article, you can use the following code:

article .post p ( margin : 0 0 12 px 0 ; )

There is nothing wrong with this approach, but if we also need to change the style of links, quotes, headings, etc. only within an article, you will need to use the prefix “article.post” for each element. This makes writing code more boring and harder to read.
In LESS we can nest these rules, giving us a shorter, more logical version of our styles. For example:

Article.post ( p( margin: 0 0 12px 0; ) a ( color: red; ) a:hover ( color: blue; ) img ( float:left; ) )

Indentation is not required, but it makes the code more readable. Nesting levels are not limited.

A ( color:red; ) p ( margin:0px; ) article ( a ( color: green; ) p ( color: #555; a ( color:blue; ) ) )

Mixins

Mixins in LESS will save you from typing unnecessary code. Have you ever had to create rounded frame in which only the top corners are rounded?

.tab ( -webkit-border-top-left-radius : 6 px; -webkit-border-top-right-radius : 6 px; -moz-border-radius-topleft : 6 px; -moz-border-radius- topright : 6 px; border-top-left-radius : 6 px; border-top-right-radius : 6 px;

And so every time... With LESS, all this can be changed by creating a mixin. Impurities are reusable elements that can be added to any element as a rule. And you don't even need to learn new syntax.

Rounded_top ( -webkit-border-top-left-radius: 6px; -webkit-border-top-right-radius: 6px; -moz-border-radius-topleft: 6px; -moz-border-radius-topright: 6px; border-top-left-radius: 6px; border-top-right-radius: 6px; ) .tab ( background: #333; color:#fff; .rounded_top; ) .submit ( .rounded_top; )

In the above code, we have defined a .rounded_top element to round the top corners. When we add it to any other element as a mixin (see .tab) we are essentially importing the rules we created for it. Thanks to this syntax, we can use any element as a mixin.

Rounded_top ( -webkit-border-top-left-radius: 6px; -webkit-border-top-right-radius: 6px; -moz-border-radius-topleft: 6px; -moz-border-radius-topright: 6px; border-top-left-radius: 6px; border-top-right-radius: 6px; ) .tab ( background: #333; color:#fff; .rounded_top; ) .submit ( .tab; background: red; )

The styles for the .submit element are rounded corners at the top, White color and red background (value #333 overridden).

Mixins with parameters

While parameter mixins sound complicated, they solve the problem in a very simple way. In the examples above, you saw how we can define an element with a 6px radius on the top corners. What if we want to create an element with a 3px radius? Should we declare different mixins for all pixel values? Of course the answer is no, we must use mixins with parameters!
They are similar to functions because they can change values ​​when they are called. Let's rewrite the example with border-radius to see how it works.

Rounded_top(@radius) ( -webkit-border-top-left-radius: @radius; -webkit-border-top-right-radius: @radius; -moz-border-radius-topleft: @radius; -moz-border -radius-topright: @radius; border-top-left-radius: @radius; border-top-right-radius: @radius; .tab ( background: #333; color:#fff; .rounded_top(6px); ) .submit ( .rounded_top(3px); )

In the above code, the radius of the .tab element is 6px, and the .submit element will have a value of 3px.

Standard values

If you usually use the same border-radius, but sometimes need a different one, you need to set the mixin to a standard value.

Rounded_top(@radius:6px) ( -webkit-border-top-left-radius: @radius; -webkit-border-top-right-radius: @radius; -moz-border-radius-topleft: @radius; -moz -border-radius-topright: @radius; border-top-left-radius: @radius; border-top-right-radius: @radius; .tab ( background: #333; color:#fff; .rounded_top; ) .submit ( .rounded_top(3px); )

In this example, .tab will get the default value of 6px and .submit will get the default value of 3px.

Multiple options

You can also use multiple parameters to identify more complex impurities.

Radius(@radius:6px) ( -webkit-border-radius: @radius; -moz-border-radius: @radius; border-radius: @radius; ) .button(@radius:3px, @background: #e7ba64, @padding: 4px) ( .radius(@radius); background:@background; border: 1px solid @background - #222; padding: @padding; ) .read_more ( .button(0px); )

In this example, class.read_more is formatted with 4px padding, background color#e7ba64 and with a border-radius of 0px.

Using all the arguments at once

Another option when using arguments is to combine them. Shorthand properties in CSS have multiple values ​​written one after the other.

div ( border :1 px solid #bbb ; )

To give all required elements a gray border, you can use this function:

Gray_border(@width: 1px, @type: solid, @color: #bbb)( border:@arguments; ) div ( .gray_border(2px, dashed); )

@arguments is a special keyword that displays all the parameters one by one in a given order. The result of the above LESS code will be:

div ( border :2 px dashed #bbb ; ) Parametric mixins without parameters

You can also use parametric mixins without parameters. This is used when you don't need to output a mixin in CSS, but want its rules to apply to the element in which it is used.

Alert ( background: red; color: white; padding:5px 12px; ) .error_message ( .alert; margin: 0 0 12px 0; )

The CSS of the above code will be like this:

.alert ( background : red; color : white; padding :5 px 12 px; ) .error_message ( background : red; color : white; padding :5 px 12 px; margin : 0 0 12 px 0 ; )

To hide the .alert class you need to set the parameter to empty.

Alert() ( background: red; color: white; padding:5px 12px; ) .error_message ( .alert; margin: 0 0 12px 0; )

The finished CSS will look like this:

.error_message ( background : red; color : white; padding :5 px 12 px; margin : 0 0 12 px 0 ; )

This is mainly used to reduce CSS size file.

Namespace

Namespaces in programming languages ​​are usually used to group elements with similar functionality. We can achieve something similar in LESS by combining our code with mixins.

#my_framework ( p ( margin: 12px 0; ) a ( color:blue; text-decoration: none; ) .submit ( background: red; color: white; padding:5px 12px; ) )

When starting work on a new site based on your framework, you can add the #my_framework link and use it without clogging up the namespace.

Submit_button ( #my_framework > .submit; )

This is also a great way to make it possible to quickly change and refine themes. If you are developing several themes for your company, then to change templates on the fly, you can put them all in one LESS file using bundles.

#fw_1 ( p ( margin: 12px 0; ) a ( color:blue; text-decoration: none; ) .submit ( background: red; color: white; padding:5px 12px; ) ) #fw_2 ( p ( margin: 8px 0; ) a ( color:red; text-decoration: underline; ) .submit ( background: blue; color: white; padding:8px 20px; ) ) .submit_button ( #fw_2 > .submit; )

As a result, we get the opportunity to speed up the writing of the layout of our project using pre-prepared mixins of our own or the framework. Moreover, using less - the readability, structure and logic of your styles increases by an order of magnitude, which will improve site support in the future.