When a programmer works on big projects then the code consists of thousands of lines, so if any other team member or any other programmer wants to refer to the code, he/she may get confused and will not be able to understand it. So, to solve this kind of problem we have CSS Grouping and Nesting concepts. These concepts make a developer’s life very easy by providing a way to write the code in a precise manner. Applying the CSS with the grouping and nesting will keep your CSS & code optimized and will make the UI load a bit faster.
Table of Contents
Nesting in CSS
The nesting concept in CSS and HTML is very helpful as it allows us to nest one style rule inside another using a CSS selector. Here the child selector has to be relative to its parent selector. The nesting property increases the readability of code and hence makes it easy to understand. Using CSS selectors, the work becomes a lot simpler as compared to creating different-different IDs and Classes for every html element.
Syntax:
class1_selector class2_selector id_selector {
property: value;
}
Example 1 (CSS):
.header {
background-color: blue;
}
.header p {
font-size: 16px;
}
.header p span:hover {
color: green;
}
Nesting Example in SCSS
.header {
background-color: blue;
p {
font-size: 16px;
span {
&:hover {
color: green
}
}
}
}
Example 2 (CSS):
table tr th {
background-color: red;
}
Example 3 (CSS):
.class1 .class2 p {
color: #404040;
}
Video Lesson for CSS Nesting
Grouping in CSS
As per the name suggests, grouping means to collect different-different things at the same place. Same goes with Grouping in HTML OR CSS. In CSS/HTML whenever we are required to apply a common property to a bunch of components then we use grouping. We select multiple elements to apply the common style property on them. This saves a lot of time and also makes our code more readable.
So why make our code lengthy and specify the same properties again and again.
Example (without CSS Grouping):
h1 {
padding: 5px;
color: grey;
}
p {
padding: 5px;
color: grey;
}
Example (with CSS Grouping):
h1, p {
padding: 5px;
color: grey;
}
In this above example, all heading is having similar style property and all the paragraphs are having the same property so we style them with the help of grouping, now wherever the h1 and p tag is used the required heading will get applied.
As shown in the above CSS grouping example, we shown how we can group various selectors by separating them with the help of comma (,).