top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is grouping in CSS and what is it used for?

+1 vote
549 views
What is grouping in CSS and what is it used for?
posted Jun 19, 2017 by Santosh Nandi

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Grouping in CSS is a technique used to reduce code redundancy and write clean, concise easy to follow code. There are going to be many instances in which multiple CSS selectors will have the same declarations. In these cases, you can group all the selectors together and write the declarations only one time. For example, if you want to apply the exact same font size and color to three different headings you can write it as shown below. However, this is a waste of space.

h1{
     font-size: 10px;
     color: green;
}

h2{
   font-size: 10px;
   color: green;
}

h3{
   font-size: 10px;
   color: green;
}
h1{
     font-size: 10px;
      color: green;
}

h2{ 
   font-size: 10px;
    color: green;
}

h3{
   font-size: 10px;
   color: green;
}

Instead you can shorten the code by grouping it. Since all three headings have the exact same declarations, you can write the three heading selectors separated by a comma and write each declaration one time reducing three blocks of code to one. The more declarations you have that are the same for different selectors, the more space you can save by condensing it using grouping. Make sure not to put a comma after the last selector as it will render the code block useless.

h1, h2, h3 {

  font-size: 10px;

  color: green;

}
h1, h2, h3 {

  font-size: 10px;

  color: green;

}

It is important to note that different types of selectors can be grouped with each other. There are three main types of CSS selectors, the element selector, id selector and class selector. The element selector uses element names in order to select the elements. The id selector selects elements by looking at the id attribute of an HTML element. It is denoted with the # character and refers to a unique element within the page. The class selector uses the class attribute to select elements. It is denoted by a period (.) followed by the class name. All three types can be grouped together like so

p, #id_value, .class {

     //Declarations

}
p, #id_value, .class {

     //Declarations

}

Another tip to keep in mind is that you can group together as many selectors as you want and any valid CSS selector can be part of a group.

Conclusion

CSS grouping can be used to condense code that has multiple selectors with the same declarations. This makes code easy to read and maintain. Also development time is significantly reduced as there is less code to write. Page load times are reduced as well when using grouping. There is no reason not to use grouping whenever applicable.

answer Jun 20, 2017 by Manikandan J
...