Nested Rules in LESS: LESS tutorial

In LESS, the nested rules is a group of CSS properties which enables using properties of one class into another class and includes class name as its properties.

Nested Rules in LESS

With LESS nesting you can simplify CSS selectors very easily. Just like HTML where first we write a parent tag then inside that tag we write its immediate children tags and inside those we write children tags of those immediate children.

Now have a look at the CSS code and see how we can simplify it with LESS. First look at the CSS code:

CSS

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

.menu {

background:#455868;

}

.menu li {

color:#EAF9F9;

}

.menu li ul{

color:#5FCF80;

}

.menu li ul li{

color:#FADFC4;

}

.menu a {

color:#00A2EA;

}

Using LESS we can write the above CSS code like this:

LESS

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

.menu {

background:#455868;

li {

color:#EAF9F9;

}

li ul{

color:#5FCF80;

}

li ul li{

color:#FADFC4;

}

a {

color:#00A2EA;

}

}

Descendants

Here is an example of descendants. Using & sign we are actually referring the parent element itself.

LESS

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

p {

color:@textColor;

font-family:@fontFamily;

font-size:@fontSize;

line-height:@lineHeight;

&.intro {

font-variant:@introFontVariant;

font-size:@introSize;

line-height:@introLineHeight;

}

.highlight {

color:@textHighlight;

font-weight:bold;

}

}

The output:

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

p{

color:#222222;

font-family:Helvetica,Arial,sans-serif;

font-size:14px;

line-height:21px;

}

p.intro{

font-variant:small-caps;

font-size:16px;

line-height:24px;

}

p.highlight{

color:#00214d;

font-weight:bold;

}

This is very important to note because there will be times when you want the descendant operator, and times when you just want to target elements with specific classes.