Difference between an id and class in HTML?

HTML id Attribute: The id attribute is a unique identifier which is used to specify the document. It is used by CSS and JavaScript to perform a certain task for a unique element. In CSS, the id attribute is written using # symbol followed by id.

Syntax:

<element id="id_name">

In CSS Stylesheet:
#id_name {
    // CSS Property
}

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML id attribute
    </title>
      
    <style>
        #geeks{
            color:green;
            font-size:25px;
        }
    </style>
</head>
  
<body style="text-align:center">
    <h1>Geeks for Geeks</h1>
    <p id="geeks">Welcome to Geeks for Geeks</p>
    <p>A Computer Science portal for geeks</p>
</body>
  
</html>                    

chevron_right


Output:

HTML class Attribute: The class attribute is used to specify one or more class names for an HTML element. The class attribute can be used on any HTML element. The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. The class name in CSS stylesheet using “.” symbol.

Syntax:

<element class="class_name>

In CSS Stylesheet:
.class {
    // CSS Property
}

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <style>
        .geeks{
            color:green;
            font-size:25px;
        }
    </style>
</head>
  
<body style="text-align:center;">
    <h1>Geeks for Geeks</h1>
    <p> Welcome to Geeks for Geeks</p>
    <p class="geeks">
        A Computer Science portal for geeks
    </p>
</body>
  
</html>                    

chevron_right


Output:

Difference between id and class attribute: The only difference between them is that “id” is unique in a page and can only apply to at most one element, while “class” selector can apply to multiple elements.



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.