We continue on our LESS articles series, In our previous articles you have read LESS introduction, Variables and Mixins. Here in this article we will learn about LESS Nested Rules which surely will help you write extremely clean and shorter style sheets.

LESS Articles Details:

1. Introduction to LESS
2. Working with Variables
3. Working with Mixins
4. Working with Nested Rules
5. Working with Functions

So Let’s get started with LESS Nested Rules

What’s LESS Nested Rules:

LESS gives you the ability to use nesting instead of combination with CSS. Lets say we have the following CSS:

  1. p {  
  2.     color#232323;  
  3.     font-familyHelveticaArialsans-serif;  
  4.     font-size15px;  
  5.     line-height25px;  
  6. }  

Now if you have few paragraph class and you need to set the font size to be a little bit bigger, have the text be small caps and the highlighted paragraph with different color.

In CSS, you will write those classes like this:

  1. p {  
  2.     color#C0FE13;  
  3.     font-familyHelveticaArialsans-serif;  
  4.     font-size15px;  
  5.     line-height25px;  
  6. }  
  7.   
  8.   
  9. p .introduction {      
  10.     font-size20px;  
  11.     line-height24px;  
  12. }  
  13.   
  14. p .highlight {  
  15.     color#00215C;  
  16.     font-weightbold;  
  17. }  

Write LESS Nested Rule

Now We’re going to write above CSS code using LESS and nested rules. A LESS nested rule starts like a regular rule. For this, we’ll also use LESS variables.

  1. @textColor: #C0FE13;  
  2. @textHighlight: #00215C;  
  3. @fontFamily: HelveticaArialsans-serif;  
  4. @fontSize: 15px;  
  5. @lineHeight: 25px;  
  6.   
  7. @introSize: 20px;  
  8. @introLineHeight: 24px;  
  9.   
  10.   
  11. p {  
  12.     color: @textColor;  
  13.     font-family: @fontFamily;  
  14.     font-size: @fontSize;  
  15.     line-height: @lineHeight;  
  16.   
  17.     .introduction {       
  18.         font-size: @introSize;  
  19.         line-height: @introLineHeight;  
  20.     }   
  21.   
  22.     .highlight {  
  23.         color: @textHighlight;  
  24.         font-weightbold;  
  25.     }   
  26.   
  27. }   

When the above LESS code is compiled will result like below:

  1. p {  
  2.   color#C0FE13;  
  3.   font-familyHelveticaArialsans-serif;  
  4.   font-size15px;  
  5.   line-height25px;  
  6. }  
  7. p .introduction {  
  8.   font-size16px;  
  9.   line-height24px;  
  10. }  
  11. p .highlight {  
  12.   color#00215C;  
  13.   font-weightbold;  
  14. }  

So here we have covered LESS nested rules. It was a shorter lessons but extremely useful if you practicing some on your own.

In the next LESS articles series, we’ll look into LESS functions and operators which is also important feature of LESS.

email