HTML Class and ID

The class and id attributes give a name to an HTML element. With these names, CSS can style the element and JavaScript can find it.


The class attribute

A class can be used on many elements, and one element can have more than one class (separated by space). In CSS, a class is selected with a dot.

<style>
  .note { background: #fff3cd; padding: 8px; }
  .big  { font-size: 20px; }
</style>

<p class="note">This is a note.</p>
<p class="note big">This is a big note.</p>
<p>This is a normal paragraph.</p>
Output in the browser

This is a note.

This is a big note.

This is a normal paragraph.


The id attribute

An id must be unique. Only one element on the page can have a given id. In CSS, an id is selected with a hash sign.

<style>
  #main-title { color: darkblue; }
</style>

<h1 id="main-title">Welcome</h1>

Difference between class and id

Pointclassid
Use onMany elementsOnly one element
Many on one elementYes, separated by spaceNo, one id only
CSS selector.classname#idname
Also used forGrouping similar elementsUnique element, links to a part of the page, JavaScript

Link to an id

An id can also be the target of a link. Add #idname at the end of the URL, and the browser scrolls to that element.

<a href="#contact">Go to Contact</a>

...

<h2 id="contact">Contact</h2>

This is how you create a link to jump to a part of a page.


Naming rules

  • Use lowercase letters, numbers and hyphens, like main-menu.
  • Do not start with a number and do not use spaces.
  • Choose names by meaning (error-message), not by look (red-text).

Summary

  • class is for groups, id is for one unique element.
  • CSS uses .class and #id.
  • An id can be a link target.
  • Next: HTML Styles.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
Do all HTML tags require both a begin and end tag?
What is the difference between HTML tags and elements?
What is an attribute in HTML?
What is the difference between DIV, SPAN and paragraph tag in HTML?
What is the difference between inline and block elements in HTML?
What are void (empty) elements in HTML?
What is the difference between id and class in HTML?