Sass Nested Rules and Properties
Sass nesting CSS selectors is similar to HTML's nested rules.
Below, we nest the styles for 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;
}
}
In this example, the ul, li, and a selectors are nested within the nav selector.
Converting the above code to CSS code, it looks like this:
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;
}
Sass Nested Properties
Many CSS properties have the same prefix, such as font-family, font-size, and font-weight, and text-align, text-transform, and text-overflow.
In Sass, we can write them using nested properties:
Sass Code:
font: {
family: Helvetica, sans-serif;
size: 18px;
weight: bold;
}
text: {
align: center;
transform: lowercase;
overflow: hidden;
}
Converting the above code to CSS code, it looks like this:
CSS Code:
font-family: Helvetica, sans-serif;
font-size: 18px;
font-weight: bold;
text-align: center;
text-transform: lowercase;
text-overflow: hidden;