CSS id and class

In our previous chapter, we learned about selectors. Now we will speak about id and class selectors frequently used to style web page elements.

CSS id selector

An ID selector is a unique identifier of the HTML element to which a particular style must be applied. It is used only when a single HTML element on the web page must have a specific style.

Both in Internal and External Style Sheets we use hash (#) for an id selector.

Example of an ID selector:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #blue {
        color: #1c87c9;
      }
    </style>
  </head>
  <body>
    <p>The first paragraph.</p>
    <p id="blue">The second paragraph.</p>
    <p>The third paragraph.</p>
  </body>
</html>

As you see, we assigned blue as id selector of the second paragraph (id="blue"), and declared its style using color property - #blue {color: #1c87c9;} in the <head> section. It means that the HTML element having id selector blue will be displayed in #1c87c9.

Check this code in our HTML online editor to see that the color of the second paragraph is #1c87c9.

CSS class selector

A class selector is used when the same style must be applied to multiple HTML elements on the same web page.

Both in Internal and External Style Sheets we use a dot (.) for a class selector.

Example of a class selector:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .blue {
        color: #1c87c9;
      }
    </style>
  </head>
  <body>
    <h2 class="blue">This is some heading.</h2>
    <p>The second paragraph.</p>
    <p class="blue">The third paragraph.</p>
  </body>
</html>

In our example, a class selector is used twice, in heading and paragraph.

As you see, we assigned blue as class selector (class="blue"), and declared its style using color property - .blue {color: #1c87c9;} in the <head> section. It means that the elements having class selector blue will be displayed in #1c87c9.

In our example, the title and the third paragraph are #1c87c9. Check it in our HTML online editor.

The Difference Between ID and Class

The difference between IDs and classes is that the first one is unique, and the second one is not. This means that each element can have only one ID, and each page can have only one element with this ID. When using the same ID on multiple elements, the code won’t pass validation. But as the classes are not unique, the same class can be used on multiple elements, and vice versa, you can use several classes on the same element.


Practice Your Knowledge

Which is the correct way to add color for a tag with class "link"?



Do you find this helpful?

Related articles