CSS Class Selector

In CSS, class selectors are displayed with a period:

.center {text-align: center}

In the above example, all HTML elements with the center class are centered.

In the following HTML code, both the h1 and p elements have the center class. This means both will follow the rules in the '.center' selector.

<h1 class="center">
This heading will be center-aligned
</h1>
<p class="center">
This paragraph will also be center-aligned.
</p>

Attention:Note: the first character of the class name cannot be a number! It will not work in Mozilla or Firefox.

Like id, class can also be used as a descendant selector:

.fancy td {
	color: #f60;
	background: #666;
	}

In this example, table cells within the larger element with the class name 'fancy' will display orange text with a gray background. (The larger element named 'fancy' may be a table or a div.)

Elements can also be selected based on their classes:

td.fancy {
	color: #f60;
	background: #666;
	}

In the above example, the table cell with the class name 'fancy' will be orange with a gray background.

<td class="fancy">

You can assign the class 'fancy' to any table element any number of times. The cells marked with 'fancy' will be orange with a gray background. The cells that are not assigned the class named 'fancy' will not be affected by this rule. Also, paragraphs with the class 'fancy' will not be orange with a gray background, of course, any other elements marked as 'fancy' will not be affected by this rule either. This is due to the way we wrote this rule, the effect is limited to the table cells marked as 'fancy' (i.e., using the td element to select the 'fancy' class).

Related Content

If you need to learn more about class selectors, please read the advanced tutorial on CodeW3C.com:CSS Class Selector Detail.