January 6, 2006

Class Aggregation in CSS

Filed under: HowTo, CSS, Web Design | Lindsay @ 8:55 am

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.

body, div, p, td, .heading, #content {
        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:

.bluefont { color: #009; }
.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.

<div class=“bluefont yellowback”>This text has a blue font and yellow background.</div>
<div class=“bottomborder padleft”>This text is padded 10px on the left and has a border on the bottom</div>
<div class=“bluefont yellowback bottomborder padleft”>This text has all of the above</div>

The above code will result in something like this:

This text has a blue font and yellow background.
This text is padded 10px on the left and has a border on the bottom
This text has all of the above

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.

(more…)

» » » » » » » »
, , , , , , ,