HTML Id & Class

In HTML, the id and class attributes are used to assign identifiers and classifications to HTML elements. These attributes are essential for styling elements with CSS, manipulating elements with JavaScript, and creating accessible web content.

The Id Attribute

The id attribute is used to uniquely identify a single HTML element. Each id must be unique within the HTML document. It is useful for styling specific elements, targeting elements with JavaScript, and linking to sections within a page.

Example: Using Id
Try yourself
        
            <p id="unique-paragraph">This is a uniquely styled paragraph.</p>
<a href="#unique-paragraph">Go to the uniquely styled paragraph</a>
        
    

In this example, the id attribute is used to style a specific paragraph and link to it within the same page.


The Class Attribute

The class attribute is used to assign one or more class names to an HTML element. Classes are not unique and can be reused across multiple elements. They are especially useful for applying the same styles to multiple elements or targeting groups of elements with JavaScript.

Example: Using Class
Try yourself
        
            <p class="styled-paragraph">This paragraph is styled with a class.</p>
<p class="styled-paragraph">This is another paragraph with the same class.</p>
        
    

In this example, the class attribute is used to style multiple paragraphs with the same class name.


Combining Id and Class

An HTML element can have both an id and a class attribute. This allows for more specific styling and manipulation with CSS and JavaScript.

Example: Combining Id and Class
Try yourself
        
            <p id="unique-class-paragraph" class="styled-paragraph">This paragraph has both an id and a class.</p>
        
    

In this example, an element has both an id and a class attribute, demonstrating how they can be used together.


Best Practices


Summary

Understanding how to use the id and class attributes is fundamental for effective HTML, CSS, and JavaScript development. The id attribute uniquely identifies elements, while the class attribute groups elements for styling and scripting purposes.