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.

Let's see an example.

<!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.

Let's see an example.

<!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.