Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CSS grouping and nesting


May 03, 2021 CSS


Table of contents


CSS grouping and nesting selectors

CSS grouping groups selectors with the same style, reducing the amount of code.

CSS nesting applies to the style of the selectors inside the selectors.


Grouping Selectors

There are many elements with the same style in the style sheet.

h1{
color:green;
}
h2{
color:green;
}
p{
color:green;
}

Try it out . . .

To minimize code, you can use the Group Selector.

Each selector is separated by a comma.

In the following example, we use a group selector for the above code:

h1,h2,p{
color:green;
}

Try it out . . .

Tip: You can group as many selectors as you want, and CSS has no restrictions on this.


Nested selectors

It may apply to the style of the selector inside the selector.

In the following example, a style is assigned to all p elements, a style of class is "marked" for all elements, and only a third style is specified for the p element within the class:

p{
color:blue;
text-align:center;
}
.marked{
background-color:red;
}
.marked p{
color:white;
}

Try it out . . .