HTML ID Attribute
The id attribute is used to give a unique identifier to an HTML element. Unlike a class, each id can be used only once per page. IDs are useful for CSS styling and JavaScript selection.
1. Basic Usage
Assign an id to an element:
<div id="unique-box"> This is a unique div. </div>
This is a unique div.
2. Styling an ID with CSS
Use #id selector in CSS:
<style>
#unique-box {
background-color: #3b82f6;
color: white;
padding: 15px;
border-radius: 8px;
}
</style>
3. Difference Between Class and ID
- Class: Can be used on multiple elements, use
.classnamein CSS. - ID: Unique to one element, use
#idin CSS.
4. Using ID in JavaScript
Access an element with its id:
<script>
const box = document.getElementById("unique-box");
box.style.fontWeight = "bold";
</script>
Next Lesson → HTML <iframe> Element
Previous Lesson → HTML Class Attribute