Why use variables in LESS preprocessor?

LESS has very useful the feature: varaibles. Imagine that  you have the CSS file and would like to change values of properties in many selectors on new value. In this situation you have to change it in a lot of places. If you use varaiables you do it one time , it save you a time in making changes. I show you it in examples below. First you see the HTML file without CSS:

<!DOCTYPE html>
<html>
<head>
<title>Animals</title>
</head>
<body>
<h1>Animals</h1>
<p>It is the list of animals.</p>
<ul>
<li>leo</li>
<li>elephant</li>
<li>cat</li>
</ul>
</body></html>

The result after run browser:

If you would like to have different colors for selectors, you have to format color property for elements, so you can use CSS file. Let’s got to new HTML code first:

<!DOCTYPE html>
<html>
<head>
<title>Animals</title>
  <link href="mystyle.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h1>Animals</h1>
<p>It is the list of animals.</p>
<ul>
<li>leo</li>
<li>elephant</li>
<li>cat</li>
</ul>
</body></html>

You add mystyle.css file, look at it:

body { color:blue; }
h1{ color:red; }
h1 + p { color:green; }
ul>li { color:orange; }
ul + p { color:pink; }

Look at the efect:

What if your boss would like to change colors of fonts on this website for only one or two colors? You notice that changes of the CSS file take a lot of time. If these selectors for change will be more, it will be hard to look for them into file to do it. But don’t worry. The LESS help you with this task. You may use LESS file, compile it and use new created CSS file.
How compile LESS you see in my posts:

Look at new HTML file  use LESS:

<!DOCTYPE html>
<html>
<head>
<title>My Box</title>
  <link href="mystyle.less" type="text/css" rel="stylesheet/less" />
  <script src="less.min.js" type="text/javascript"></script>
</head>
<body>
<h1>Animals</h1>
<p>It is the list of animals.</p>
<ul>
<li>leo</li>
<li>elephant</li>
<li>cat</li>
</ul>
<p>Text after ul element.</p>
<p>Next text after paragraph.</p>
</body>
</html>

And look at LESS file(mystyle.less):

@mainColor: green;
@headerColor: blue;
@pColor: blue;

  body { color:  @mainColor }
  h1   { color:  @headerColor; }
h1 + p { color:  @pColor; }
 ul>li { color:  @pColor; }
ul + p { color:  @pColor; }

Run website see the result:

Of course, it is very simple example. I’m only going to show you how use variables in LESS. As you see the variable starts with ‘@’ sign. The value is assign to the varaible after ‘:’ sign. After definition of variables you may use them in the file. Instead of use value for value of the property for selector, you set name of the variable, defined above. Each definition of variable is separated by ‘;’ sign.

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.