CSS id and class
id and class selectors
If you want to set CSS styles on HTML elements, you need to set the "id" and "class" selectors on the elements.
The id selector
The id selector can specify a particular style for an HTML element marked with a specific id.
HTML elements set the id selector with the id attribute; in CSS, the id selector is defined with "#".
The following style rule applies to the element with attribute id="para1":
Example
#para1
{
text-align:
center
;
color:
red
;
}
Try it »
ID attributes should not start with a number; IDs starting with a number do not work in Mozilla/Firefox browsers.
The class selector
The class selector is used to describe the style of a group of elements. Unlike the id selector, a class can be used on multiple elements.
The class selector is represented by the class attribute in HTML; in CSS, the class selector is shown with a dot . :
In the following example, all HTML elements with the center class are centered.
Example
.center
{
text-align:
center
;
}
Try it »
You can also specify that a particular HTML element uses a class.
In the following example, all p elements use class="center" to center the text of the element:
Example
p
.center
{
text-align:
center
;
}
Try it »
Multiple class selectors can be separated by spaces:
Example
.center
{
text-align:
center
;
}
.color
{
color:
#ff0000
;
}
Try it »
The first character of a class name cannot be a number! It will not work in Mozilla or Firefox.