CSS Id and Classes

id and class selector

If you want to set CSS styles in HTML elements, you need to set “id” and “class” selectors in the elements.

id selector

The id selector can specify a specific style for the HTML element marked with a specific id.

HTML elements use id attributes to set id selectors, and id selectors in CSS are defined by “#”.

The following style rules apply to the element attribute id=”para1″:

Example

#para1
{
    text-align:center;
    color:red;
}
The ID attribute should not start with a number. IDs starting with a number will not work in Mozilla/Firefox browsers.

class selector

The class selector is used to describe the style of a group of elements. The class selector is different from the id selector. Class can be used in multiple elements.

The class selector is represented by the class attribute in HTML, and in CSS, the class selector is represented by a dot “.”:

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

Example

.center {text-align:center;}

You can also specify specific HTML elements to use class.

In the following example, all p elements use class=”center” to center the text of the element:

Example

p.center {text-align:center;}
Numbers cannot be used in the first character of the class name! It does not work in Mozilla or Firefox.