The HTML id attribute specifies a unique identifier for a single element within an HTML document. Unlike classes, an id value must be completely unique across the entire page.
You assign an ID using the id attribute on any HTML tag. In CSS, IDs are selected using a hash (#) symbol.
<!-- Unique element declaration -->
<header id="main-header">
<a href="#contact-form">Jump to Contact</a>
</header>
/* Target unique ID in CSS */
#main-header { background-color: #1e293b; }
Primary roles of the id attribute:
document.getElementById('user-avatar')).<a href="#section-2">) for smooth page scrolling.<label for="email"> directly to <input id="email"> for accessibility.flowchart TD
A["HTML id='user-profile'"] --> B["JS Target (getElementById)"]
A --> C["Anchor Scroll (#user-profile)"]
A --> D["Form Label Binding (for='user-profile')"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML ID Attribute Demonstration</title>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<!-- Navigation jump link -->
<a href="#feedback-section" style="color: #38bdf8;">Jump to Feedback Form</a>
<div style="height: 300px;"></div> <!-- Spacing for scroll demo -->
<!-- Target section with unique ID -->
<section id="feedback-section" style="background-color: #1e293b; padding: 1.5rem; border-radius: 8px;">
<h2>Feedback Form</h2>
<form>
<!-- Label linked to input via ID -->
<label for="user-email" style="display: block; margin-bottom: 0.5rem;">Your Email:</label>
<input type="email" id="user-email" style="padding: 8px; border-radius: 4px; border: 1px solid #334155; width: 250px;">
</form>
</section>
</body>
</html>
<label for> with <input id>: Ensures screen reader users can hear the input field name when focusing on form controls.Create a form containing a <label> with a for attribute and a matching <input> with the same id attribute value!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.