# Nesting
- While HTML has a clear nested hierarchy (visualized in your editor by the increasing indentation when you move deeper in the DOM of your page), CSS has not!
- Using Sass, you can
- nest your CSS selectors in a way that follows the same visual hierarchy of your HTML
- write one style rule inside another
# Basic Nesting
- Suppose we want the
p
tag in thefooter
to have a different (top and bottom)padding
, without affecting the other paragraphs of our page- Using CSS, we would write
footer p { padding: 1rem 0; }
- Using the Sass nesting technique, this style rule can be inserted within the style rule for
footer
- Using CSS, we would write
SCSS
CSS
@use "sass:color"; $sasscolor: #cf649a; footer { color: inherit; background-color: color.scale(color.invert($sasscolor), $lightness:75%); p { padding: 1rem 0; } }
Copied!
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
REMARKS
- Obviously, you are not restricted to 2 levels of nesting. Suppose you would want to style the
a
tag(s) within the paragraphs of thefooter
(without affecting the othera
tags), you could write something like
footer { ... p { ... a { ... } } }
Copied!
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- Besides the descendant (space) combinator, you can also use nesting with the other combinator selectors:
div { ... > p { ... } }
Copied!
1
2
3
4
5
6
7
2
3
4
5
6
7
div { ... + p { ... } }
Copied!
1
2
3
4
5
6
7
2
3
4
5
6
7
div { ... ~ p { ... } }
Copied!
1
2
3
4
5
6
7
2
3
4
5
6
7
# Advanced nesting with the parent selector
- The parent selector
&
is a Sass selector that is used in nested selectors to refer to the outer (parent) element - This selector is often used in combination with nesting to style the different link states:
SCSS
CSS
@use "sass:color"; $sasscolor: #cf649a; a { font-weight: bold; text-decoration: none; color: color.scale($sasscolor, $lightness:-50%); background-color: inherit; &:focus { outline: 2px solid $sasscolor; } &:hover { text-decoration: underline; } }
Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
READING TIP