Nesting is used to make your code follow some visual hierarchy. It makes your code, simple, clean and less complex. You must be very careful while nesting because overly nested rules may cause complexity and it proves hard to maintain.

Let's take an example. Suppose you have to write a CSS code for a website which has three paragraphs, a standard paragraph, an intro paragraph and a highlighted paragraph. All the paragraphs are different in font size and caps. So you have to define all three differently.

For example:

CSS code:

  1. p {  
  2.     color: #232323;  
  3.     font-family: Helvetica, Arial, sans-serif;  
  4.     font-size: 14px;  
  5.     line-height: 21px;  
  6. }  
  7.   
  8. p .intro {  
  9.     font-variant: small-caps;  
  10.     font-size: 16px;  
  11.     line-height: 24px;  
  12. }  
  13.   
  14. p .highlight {  
  15.     color: #00214D;  
  16.     font-weight: bold;  
  17. }  

Less nesting facilitates you to write the above CSS code in a nested manner where you don?t need to write the paragraph code repeatedly.

Equivalent Less file:

  1. @textColor: #232323;  
  2. @textHighlight: #00214D;  
  3. @fontFamily: Helvetica, Arial, sans-serif;  
  4. @fontSize: 14px;  
  5. @lineHeight: 21px;  
  6.   
  7. @introSize: 16px;  
  8. @introLineHeight: 24px;  
  9. @introFontVariant: small-caps;  
  10.   
  11. // Less for Paragraph  
  12. // ------------------  
  13. p {  
  14.  color: @textColor;  
  15.  font-family: @fontFamily;  
  16.  font-size: @fontSize;  
  17.  line-height: @lineHeight;  
  18.  .intro {  
  19.   font-variant: @introFontVariant;  
  20.   font-size: @introSize;  
  21.   line-height: @introLineHeight;  
  22.  }   
  23.  .highlight {  
  24.   color: @textHighlight;  
  25.   font-weight: bold;  
  26.  }   
  27. }