What Are ID and Class?

CSS is used to define the layout, font, color, and other aspects of webpages. CSS is also used to control the display of multiple webpages.

ID and Class

ID and class are two of the most important concepts in CSS. IDs and classes are used to identify and group elements on a page. IDs are unique and can be used to identify a single element on a page. Classes, on the other hand, can be used to group multiple elements on a page.

CSS selectors are used to “find” (or select) the HTML elements you want to style.

You can also define your own selectors in the form of Class and ID selectors.

In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”).

ID:

An ID is a unique identifier that is used to identify a single element on a page. IDs are written in the form of a name or number preceded by a hash (#). For example, an HTML element with an ID of “main-content” would be written as “#main-content” in the CSS file. IDs can be used to target a specific element on a page and apply styles to it.

  • Each element can have only one ID
  • Each page can have only one element with that ID
<button id="btn-save">Save</button>

Css

#btn-save{
    background-color: #ccc;
}

Class:

Classes are used to group multiple elements on a page. Classes are written in the form of a name preceded by a period (.). For example, an HTML element with a class of “heading” would be written as “.heading” in the CSS file. Classes can be used to apply the same styles to multiple elements on a page.

Classes are not unique

  • You can use the same class on multiple elements.
  • You can use multiple classes on the same element.
<button class="btn-save">Save</button>

CSS

.btn-save{
    background-color: #ccc;
}