Sass : Nesting selectors and properties
Sass is a well known framework of CSS. It’s an efficient and reliable tool, which gives us great power to write CSS in precise way.
Sometimes we (Front-end Developers) all wonder that we wouldn’t be able to enjoy writing CSS. However, as soon as Sass came in our life, we discovered this was the way to go when working with CSS. Please visit this link to know how to install Sass in your machine.
In this blog we’ll talk about “Nesting in Sass”. This is the first feature you need to know when you start working with Sass. Nesting allows us to use shortcuts to create our rules.
What is Nesting ?
Nesting allows us to write selector in the structure of our HTML. As I mentioned above, it allows us to use shourcuts to create our rules. Lets have a look at the example below.
[html]
div {
font-size: 14px;
span{
color : black;
}
}
[/html]
The div
element encloses the span
element and it will comply to.
[html]
div { font-size: 14px; }
div span { color: black; }
[/html]
This is the simplest example of nesting in Sass. You just need to enclose a selector(s) inside the curly braces of another selector. Lets have a look at some more examples of nesting with parent selector. We need to use an ampersand (&) sign with colon (:) to specify where the parent selector needs to be placed.
[html]
a {
color: #999;
&:hover {
color: #777;
}
&:active {
color: #888;
}
}
[/html]
This complies to:
[html]
a { color: #999; }
a:hover { color: #777; }
a:active { color: #888; }
[/html]
Now, we have a decent idea of nesting in Sass but one of the cool features in that is, we can nest CSS properties as well. Many of us might not be aware of nesting CSS properties. This is really awesome, which I liked. Lets have a look at the below example.
[html]
.btn {
text: {
decoration: underline;
transform: lowercase;
}
border:{
radius:5px;
color: green;
};
}
[/html]
This complies to:
[html]
.btn {
text-decoration: underline;
text-transform: lowercase;
border-radius: 5px;
border-color: green;
}
[/html]
Nesting can be extended to as many levels as you wish. It means you can nest elements within an element that comes nested inside another elements but it is generally good practise to avoid nesting deeper than three or four levels. Anything more than that starts affecting the readability and maintainability of code.
Hope this helps!
Linkedin
Twitter