Nesting | Sass
Sass Nesting
Saas Nesting
Nesting is one of the basic reason that a developer needs Sass. CSS support logical nesting but not code block nesting. Sass supports the nesting code within each other. There are two types of nesting:
- Property Nesting
- Rule Nesting
Sass Property Nesting
This is observed that mostly used CSS properties have the same prefix e.g. font-
,text-
,background-
etc.
For convinience Sass allows writing the prefix once and within the scope there rest of the perty names.
You just have to add colon (:) after the prefix e.g. font:
. Take a look at the following example:
body {
font: {
family: Verdana;
size: 1.5em;
style: normal;
}
}
div {
text: {
align: left;
transform: capitalize;
decoration: normal;
}
}
p {
background: {
color:blue;
image:url('/img/p.jpg');
repeat:no-repeat;
attachment: fixed;
}
}
The code above will be transpiled to the following:
body {
font-family: Verdana;
font-size: 1.5em;
font-style: normal;
}
div {
text-align: left;
text-transform: capitalize;
text-decoration: normal;
}
p {
background-color: blue;
background-image: url("/img/p.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
}
Sass Rule Nesting
Sass rule nesting works just like CSS selectors do for HTML. Advantage of Sass rule nesting is that selectors repetitions are avoided and the rules are more easily readable to minimize the designing flaws between HTML and CSS. Following examples clears this.
div{
background:black;
color:white;
font-size:12pt;
ul,ol{
padding-left: 20px;
margin:10px;
li{
color:blue;
font-weight:bold;
}
}
p{
color:orange;
span{
color:maroon;
background-color:white;
}
}
}
Following is the output:
div {
background: black;
color: white;
font-size: 12pt;
}
div ul, div ol {
padding-left: 20px;
margin: 10px;
}
div ul li, div ol li {
color: blue;
font-weight: bold;
}
div p {
color: orange;
}
div p span {
color: maroon;
background-color: white;
}
Now just imagine the effort of developer and the mainter of the code if css would written manually.