X

Headline

This is an important message requiring you to make a choice if you're based in the EU.

CSS id and class

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

CSS id selector

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

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

Example of using 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 with 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

Class selector is used when the same style should be applied to multiple HTML elements on the same web page.

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

Example of using 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 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 with 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. In case of 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