Multiple CSS classes on a single element

Oct 19, 2006

Do you worry about repeating styles in your CSS? If a lot of your CSS classes use a common style like text-align: center; or color: #CCC:, you can actually create a single class for each of these styles and save a ton (well, not really, maybe one or two KB) of bandwidth on page load. A lot of people don't know about assigning multiple CSS classes to a single element.

Let's say you have a <p> tag that you want to add specific styles such as margin and padding, plus some pretty common(throughout your Web site) styles like text-align: center; and color: #666;. Instead of writing each of these styles for every element that they appear on, you can write a single class for each style, or group of styles that usually appear together, and just add it to the class application on the desired element.

Your stylesheet might look like this:

.specific_style {
  margin: 5px 10px;
  padding: 2px;

.center_text { text-align: center; }

.dark_gray { color: #666; }

And then you can add multiple classes to any element by separating them with a space, like so:

<p class="specific_style center_text dark_gray">Lorem ipsum dolor sit amet.</p>

This will apply the specific_style class as well as centering the text and coloring it dark gray. This is a wonderful way to keep your CSS DRY. Be careful though. Don't overuse this method or your elements will have classes a mile long. Very handy when used properly!

Tagged: xhtmlcss