HTML Id
Learn how to use unique identifiers for HTML elements
🆔 What is HTML Id?
The id attribute provides a unique identifier for an HTML element. Each id must be unique within the page and is used for specific targeting.
<h1 id="main-heading">Welcome to My Site</h1>
<p id="intro-text">This is the introduction.</p>
Output:
Welcome to My Site
This is the introduction.
Key Id Concepts
Unique
Each id must be unique on the page
<div id="header">Header</div>
Linking
Create internal page links
<a href="#section1">Go to Section</a>
CSS Styling
Style specific elements with CSS
#header {
background: blue;
}
JavaScript
Target elements with JavaScript
document.getElementById("header")
🔹 Basic Id Usage
Here's how to use ids in HTML:
<!-- Unique identifiers -->
<header id="main-header">Site Header</header>
<nav id="navigation">Navigation Menu</nav>
<main id="content">Main Content</main>
<footer id="site-footer">Footer</footer>
Output:
🔹 Internal Links with Id
Use ids to create links within the same page:
<!-- Navigation links -->
<a href="#section1">Go to Section 1</a>
<a href="#section2">Go to Section 2</a>
<!-- Target sections -->
<h2 id="section1">Section 1</h2>
<p>Content of section 1...</p>
<h2 id="section2">Section 2</h2>
<p>Content of section 2...</p>
Output:
🔹 Id vs Class
Understanding the difference between id and class:
<!-- Id: Unique, one per page -->
<div id="header">Main Header</div>
<!-- Class: Reusable, multiple elements -->
<p class="highlight">Text 1</p>
<p class="highlight">Text 2</p>
<p class="highlight">Text 3</p>
Output:
Text 1
Text 2
Text 3