# 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 the footer 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




 
 
 
 
 
 
 
 

@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

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 the footer (without affecting the other a tags), you could write something like
footer {
  ...
  p {
    ... 
    a {
      ...
    }
  }
}
Copied!
1
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
div {
  ... 
  + p {
    ...
  }
}

Copied!
1
2
3
4
5
6
7
div {
  ... 
  ~ p {
    ...
  }
}

Copied!
1
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:










 
 
 

 
 
 


@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

# Example 1C

Last Updated: 3/8/2021, 8:17:17 PM