(click anywhere to close)
OPEN MENU

[SASS] Nesting

category: Website | course: SASS | difficulty:
IN PRINT
QUICK CONTENTS:Intro
1. Parents
2. Media Queries

One of the reasons HTML is so simple and easy to use, is its clear nesting structure – which CSS unfortunately lacks. Again, SASS comes to the rescue!

We can nest selectors inside other selectors, simply by placing them within each other. This way we can create styles for different elements within the same parent element, without having to retype the path to the parent every time.

selector { otherselector { styles } anotherselector { styles } general styles }
#nav {
	a {
		background-color: lightblue;
	}

	background-color: blue;
}

/*** OUTPUTS TO ***/
#nav {
	background-color: blue;
}

#nav a {
	background-color: lightblue;
}

Be aware, though, that overly nested rules create overqualified CSS, unnecessarily increasing file size and complexity. If you don’t necessarily need to specify something in a selector, by all means, leave it out. Keep things simple, keep things short.

Parents

Sometimes when you’re nested, you want to access your parent. For example, if you want to add pseudo-elements or pseudo-classes. This is done with the & symbol.

#nav {
	//Executed when user hovers over #nav element
	&:hover {
		background-color: lightblue;
	}
}

Media Queries

Media queries work exactly like in regular CSS, but with SASS you can also nest them inside other selectors. This way, you can put media queries close to the element they belong to, and make them more specific.

#nav {
	width:600px;
	margin:auto;

	//Special styles for #nav for certain maximum screen size
	@media screen and (max-width:600px) {
		width:100%;
		margin:0;
	}
}
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)