SASS Series

Learning SASS – Part 2: Nesting

Posted on by

In part 1, we covered how to set up your file structure and imports and now we’re ready to move on to another great feature of SASS. In this part, I’ll be discussing nesting and it’s awesomeness.

Nesting Basics

A lot of times while you’re writing your CSS, you have several selectors that begin with the same thing and you find yourself writing them over and over which is just a bore. Nesting removes this and really makes writing your CSS more efficient and organized. With SASS you can nest your child selectors within your parent selectors. The best way to grasp it, is to just see it. I’ll be using a navigation list as an example in this post to show you the differences.

Here is how you could write a basic navigation list using nesting…

SCSS


.nav {
	width:100%;
	background:black;

	ul {
		list-style:none;

		li {
			margin:10px;

			a {
				color:white;
			}
		}
	}
}

Is that not much simpler and organized? Well, maybe not everyone would agree, but I sure think so. Let’s take a look at what this will be outputted to in your CSS file.

Output in CSS file

CSS


.nav {
	width:100%;
	background:black;
}
.nav ul {
	list-style:none;
}
.nav ul li {
	margin:10px;
}
.nav ul li a {
	color:white;
}

Personally, I’ll take the nesting method all day long. Once you start getting a little more deep in to your CSS and structures, nesting will definitely become one of your best friends in keeping your code organized and very specific where it needs to be.

Using Pseudoclasses

What happens when you’re nesting and you have to add in a pseudoclass such as a :hover or :active? No problem, those can easily be nested as well with the special character, &.

SCSS


a {
	color:black;

	&:hover {
		color:white;
	}
}

When Not to Nest

As cool and helpful nesting is, it shouldn’t be used in every situation. I would recommend only nesting when necessary and when very specific selectors need to be targeted. Styles that are going to be applied site-wide shouldn’t be nested. It will end up compiling much more CSS than you need giving you a larger file size.

In the next part, I’ll be going over how to use variable in your stylesheets which allows you to declare values for CSS properties such as color, numbers, and font stacks.

The SASS Series

Leave a Reply