Sass - Nested Rules


Advertisements


Description

Nesting is combining of different logic structures. Using SASS, we can combine multiple CSS rules within one another. If you are using multiple selectors, then you can use one selector inside another to create compound selectors.

Example

The following example describes the use of nested rules in the SCSS file −

<html>
   <head>
      <title>Nested Rules</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css" />
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   </head>

   <body>
      <div class = "container">
         <h1>My First Heading</h1>
         <p>It is a CSS pre-processor which helps to reduce repetition with CSS and save the time. </p>
         <p>It is more stable and powerful CSS extension language.</p>
         <div class = "box">
            <h1>My Second Heading</h1>
            <p>It is initially designed by Hampton Catlin and developed by Natalie Weizenbaum in 2006.</p>
         </div>
      </div>
   </body>
</html>

Next, create file style.scss. Note the .scss extension.

style.scss

.container{
   h1{
      font-size: 25px;
      color:#E45456;
   }
   
   p{
      font-size: 25px;
      color:#3C7949;
   }

   .box{
      h1{
         font-size: 25px;
         color:#E45456;
      }
      
      p{
         font-size: 25px;
         color:#3C7949;
      }
   }
}

You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −

sass --watch C:\ruby\lib\sass\style.scss:style.css

Sass CSS Extensions

Next, execute the above command, it will create the style.css file automatically with the following code −

The generated style.css is as shown below −

style.css

.container h1 {
   font-size: 25px;
   color: #E45456;
}

.container p {
   font-size: 25px;
   color: #3C7949;
}

.container .box h1 {
   font-size: 25px;
   color: #E45456;
}

.container .box p {
   font-size: 25px;
   color: #3C7949;
}

Output

Let us carry out the following steps to see how the above given code works −

  • Save the above given html code in nested_rules.html file.

  • Open this HTML file in a browser, an output is displayed as shown below.

Sass CSS Extensions
sass_css_extensions.htm

Advertisements
E-Books Store