Advanced Less Tutorial : Variables

In my previous Less Tutorial, I explained you about the basic features of less and how to use them. This tutorial is for advanced users who is already experienced in coding with less. If you are new to less, I recommend you to follow “Less tutorial for beginners” first so that you can understand this tutorial easily.
less variable

In this tutorial I will talk about only “Less Variable” which is one of the important features of the Less and you will learn how to use Less variable with advanced examples.

There is no doubt variables in CSS will be a thing of the future. We will enjoy CSS variables in near future, you can check spec here. Variables in LESS work like they do in other programming languages. If you are a experienced developer, the term variable is more common for you and if not you will know what is Less variables and how to use them. Less variables are some predefined values which can be used in multiple place when required. Less variable can be used to store a value and then use the variable instead of the value itself whenever you need.

 A Simple Example

 Here is a simple example which defines, color, font size and font family for a paragraph.

@roboto:'Roboto', sans-serif;

  font-family: @roboto;
  font-size: @15px;

Here is compiled css.

.danger {
  color: #ff0000;
  font-family: 'Roboto', sans-serif;
  font-size: 0.938rem;

Little advanced variable 

We can define a variable inside specific rule, so that the variable will work inside that rule only.

@bg:rgb(255, 255, 255);
  background: @bg;
    @bg:rgb(1, 125, 0);
    background: @bg;
      background: @bg;
  background: @bg;

In above less style, I have defined a variable @bg, which can be used anywhere but for container, @bg value is different which will work only inside container. That can be more clear with following compiled css.

body {
  background: #ffffff;
body .container {
  background: #017d00;
body .container .col-1 {
  background: #017d00;
footer {
  background: #ffffff;

Some advanced examples of Less variables 


@blue-md:   #ff0;
@blue-dk:   #0ff;

.color(@color) {
    body.@{color} { background-color: ~"@{@{color}-dk}";
        #container { background-color: ~"@{@{color}-md}";
         p { color: ~"@{@{color}-md}"; }

1. Compiled CSS {
  background-color: #00ffff;
} #container {
  background-color: #ffff00;
} #container p {
  color: #ffff00;

2. Less

@red:   #232;
@green: #565;
@blue:  #898;

.theme (@color) {
  background-color: @color - #111;
  #container {
    background-color: @color;
    p { color: @color + #111; }
} {

2. Compiled CSS {
  background-color: #112211;
} #container {
  background-color: #223322;
} #container p {
  color: #334433;
Advanced Less Tutorial : Variables Reviewed by Prem Regmi on 9:27:00 AM Rating: 5

No comments:

All Rights Reserved by Next Bootstrap © 2014 - 2015
Designed by Themes24x7

Contact Form


Email *

Message *

Powered by Blogger.