Home Page -> CSS Tips -> CSS Mix and Match Classes

CSS: Mix and match Classes

Information: CSS 2 stands for Cascading Style Sheets, level two.
Feature: CSS 2 has capabilities that make your stylesheets smaller and easier to use.

Take a look at the two short paragraphs at the right side of the screen.

Using CSS level one, you'd have to establish different classes for each of the boxes:

.info { 
	border: dotted 2px black;
	width: 200px;
	margin: 6px 3px 6px 3px;
	padding: 4px;
	background-color: #ffccff;
}

.feature { 
	border-style: dotted 2px black;
	width: 200px;
	margin: 6px 3px 6px 3px;
	padding: 4px;
	background-color: #ffffcc;
}

They're both the same except for the background color. If you wanted other classes of boxes, all using the same border but with different background colors (yellow for warnings, blue for “cool stuff,” etc.) you'd have a lot of duplication. CSS2 solves this problem by letting you specify more than one class name in a class= attribute.

Let's extract the border information into one class, and the background colors that we want into separate classes:

.bordered { 
	border: dotted 2px black;
	width: 200px;
	margin: 6px 3px 6px 3px;
	padding: 4px;
}

.info { background-color: #ffccff; }
.feature { background-color: #ccffcc; }
.warning { background-color: #ffffcc; }
.coolness { background-color: #ccccff; }

Now you can combine borders and background colors by specifying multiple classes. The class names may occur in any order and must be separated by whitespace.

This is an energy-saving radio.
Do not operate this radio under water.
This radio has a USB port for Internet connectivity.
	<div class="bordered feature">
		This is an energy-saving radio.
	</div>
	<div class="bordered warning">
		Do not operate this radio under water.
	</div>
	<div class="coolness bordered">
	   This radio has a USB port for Internet
	   connectivity.
	</div>

More Information

The documentation for this technique, and many other interesting ways to specify a style selector, is in the CSS2 specification, section 5.8.