Welcome Guest! (App Version 5.16)

websitnero logo name

Sass Nesting

What is Nesting in Sass?

Nesting means putting items in an hierarchy. Nesting creates items one inside another logically. While writing pure CSS every new selector is to be written in a new line, but in Sass you can logically put elements inside one another as per dom-skeleton in html and the code will be finally parsed or compiled to pure CSS. The benefit is the readability and understanding that an end user gets just by reading the code.

Look at the example below to understand more:

main.scss:

body {
  background: red;
  color: yellow;

  div {
    background: pink;
    padding: 5px;
    color: orange;

    p {
      border: 2px solid blue;
      color: #fff;
      background: #333;

      a {
        color: yellow;
      }
    }
  }
}
				

main.css (compiled):

body {background: red; color: yellow;}
body div {background: pink; padding: 5px; color: orange;}
body div p {border: 2px solid blue; color #fff; background: #333;}
body div p a {color: yellow;}

index.html:

This is body.
This is a div.

This is a paragraph. Lets go to google now.

Use of & to use pseudo-classes and pseudo-elements

While nesting sometimes you might be needing to use pseudo-classes and pseudo-elements. So, for these situations just use the & character and code-along as follows:

main.scss:

p {
  border: 2px solid blue;
  color: #fff;
  background: #333;
  padding: 5px 10px;

  &:hover {
    color: orange;
    background: red;
  }

  &::after {
    content: "this is added!!!"
  }

  a {
    color: yellow;

    &:hover {
      color: violet;
      background: yellow;
    }
  }
}
				

main.css (compiled):

p {border: 2px solid blue; color: #fff; background: #333;padding: 5px 10px;}
p:hover {color: orange; background: red;}
p::after {content: "this is added!!!";}
p a {color: yellow;}
p a:hover {color: violet; background:yellow;}

index.html:

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.