Sass Nested Rules and Properties
Sass nested CSS selectors are similar to HTML nesting rules.
Below we nest the styles of a navigation bar:
Sass code:
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
display: inline-block;
}
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
display: inline-block;
}
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
In the example, the ul, li, and a selectors are all nested within the nav selector.
Convert the above code to CSS code, as shown below:
CSS code:
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
Sass Nested Properties
Many CSS properties have the same prefix, for example: font-family, font-size, and font-weight, text-align, text-transform, and text-overflow.
In Sass, we can use nested properties to write them:
Sass code:
font: {
family: Helvetica, sans-serif;
size: 18px;
weight: bold;
}
text: {
align: center;
transform: lowercase;
overflow: hidden;
}
family: Helvetica, sans-serif;
size: 18px;
weight: bold;
}
text: {
align: center;
transform: lowercase;
overflow: hidden;
}
Convert the above code to CSS code, as shown below:
CSS code:
font-family: Helvetica, sans-serif;
font-size: 18px;
font-weight: bold;
text-align: center;
text-transform: lowercase;
text-overflow: hidden;
font-size: 18px;
font-weight: bold;
text-align: center;
text-transform: lowercase;
text-overflow: hidden;