css

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.  

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.

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

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.  

Comments