HTML Id Attribute
The id attribute in HTML is used to provide a unique identifier for a specific element on a webpage.
The id attribute value must be unique within the entire HTML document, meaning no other element in the same document can have the same id. This uniqueness makes it a powerful tool for targeting and styling specific elements, as well as for scripting and linking purposes.
Here's the basic syntax for adding an id attribute to an HTML element:
Using The id Attribute
The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique within the HTML document.
The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id.
The syntax for id is: write a hash character (#), followed by an id name. Then, define the CSS properties within curly braces {}.
In the following example we have an <h1> element that points to the id name "myHeader". This <h1> element will be styled according to the #myHeader style definition in the head section:
Example
<html> <head> <style> #myHeader { background-color: lightblue; color: black; padding: 40px; text-align: center; } </style> </head> <body> <h1 id="myHeader">My Header</h1> </body> </html>
You can click on above box to edit the code and run again.
Output
My Header
Difference Between Class and ID
A class name can be used by multiple HTML elements, while an id name must only be used by one HTML element within the page:
Example
<style> /* Style the element with the id "myHeader" */ #myHeader { background-color: lightpink; color: black; padding: 40px; text-align: center; } /* Style all elements with the class name "city" */ .city { background-color: blue; color: white; padding: 10px; } </style> <h1 id="myHeader">My Cities <h2 class="city">Ranchi</h2> <p>Ranchi is the capital of Jharkhand.</p> <h2 class="city">Patna</h2> <p>Patna is the capital of Bihar.</p> <h2 class="city">bhuneshwer</h2> <p>bhuneshwer is the capital of Orisha.</p>
You can click on above box to edit the code and run again.
Output
My Cities
Ranchi
Ranchi is the capital of Jharkhand.
Patna
Patna is the capital of Bihar.
bhuneshwer
bhuneshwer is the capital of Orisha.