The id selector uses the id attribute of an HTML element to select a specific element. An id should be unique within a page, so the id selector is used if you want to select a single, unique element. To select an element with a specific id, write a hash character, followed by the id of the element.

Classes, like ID’s, can also be used to in JavaScript scripts, but unlike ID’s, they can be used multiple times in the same HTML document. This separation of content from presentation is what makes sites powered by CSS more robust, but some don’t know the full extent to which they can use classes.

ID’s are unique

  • Each element can have only one ID
  • Each page can have only one element with that ID

Classes are NOT unique

  • You can use the same class on multiple elements.
  • You can use multiple classes on the same element.

Examples:

The style rule below will be applied to the HTML element with id=”id1″:

#id1 {
    text-align: center;
    color: red;
}

In the example below, all HTML elements with class=”center”:

.center {
    text-align: center;
    color: red;
}

In the example below we have grouped the selectors from the code above:

h1, h2, p {
    text-align: center;
    color: red;
}