Class Aggregation in CSS
CSS is “teh awesome”. Being able to control the look and feel of an entire website with one file while simultaneously keeping your markup clean and creating a separation between presentation and code is a wonderful thing. But sometimes, especially for beginners, CSS itself isn’t necessarily used or written in the most efficient way. There’s a powerful feature in CSS that I don’t see a lot of people using or talking about and I thought I’d share it since it’s been useful to me in several projects.
Most people know about grouping: you can write your CSS classes with multiple selectors if they will share the same attributes.
padding: 0;
margin: 0;
background-color: #fff;
}
Grouping can be useful and help keep your CSS from getting bulky with duplicate classes, but there’s an opposite approach that can also reduce duplication of code while providing some other benefits.
I don’t know if there’s an actual name for this practice but I call it “aggregation”. You may create CSS classes for specific attributes and apply them simultaneously to your HTML elements. The styles will aggregate and all of them will then display on the element:
.padleft { padding: 0 0 0 10px; }
.yellowback { background-color: #ffd; }
.bottomborder { border-bottom: solid 1px black;}
You can apply the classes to HTML elements by separating them with spaces in the class attribute.
The above code will result in something like this:
Why is this useful? Because you can separate things like changing the colors of an element from it’s layout information and only apply the styles to the element as needed.










