Skip to main content

Sass: Nested Rules

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

Example of nested rules in a 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>H1 Heading</h1>
<p>A paragraph</p>
<p>Another paragraph</p>
<div class="box">
<h1>Another H1 Heading</h1>
<p>Another paragraph</p>
</div>
</div>
</body>
</html>

and the style.scss file:

.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;
}
}
}

Then you tell Sass to watch the file and update the CSS when the file changes:

sass --watch my\path\style.scss:style.css

The generated style.css files is as shown below:

.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;
}

Table of Contents