HTML id Attribute

🌐 HTML id Attribute

The HTML id Attribute is used to uniquely identify a single element on a page.

It is commonly used for CSS styling, JavaScript access, and page navigation (anchors).


 1. What Is the id Attribute?

  • Assigns a unique name to an HTML element

  • Must be unique (only one element per page)

  • Used with CSS (#) and JavaScript

<h1 id="mainTitle">Welcome</h1>

 2. Basic Example

HTML

<p id="intro">This is the introduction.</p>

CSS

#intro {
color: blue;
font-size: 18px;
}

✔ Only the element with id="intro" gets styled


 3. Using id with <div>

<div id="header">Header Section</div>
<div id="content">Main Content</div>
<div id="footer">Footer</div>
#header { background: #333; color: white; }
#content { padding: 15px; }
#footer { background: #eee; }

✔ Very common for page layout


 4. id in JavaScript (Very Common)

<p id="msg">Hello</p>

<script>
document.getElementById(“msg”).style.color = “red”;
</script>

✔ Direct access to a single element


 5. id for Page Navigation (Anchor Links)

<a href="#contact">Go to Contact</a>

<h2 id=“contact”>Contact Us</h2>

✔ Clicking the link scrolls to the element with that id


 6. id vs class (Important Difference)

Feature id class
Unique
Reusable
CSS selector #id .class
JavaScript getElementById() getElementsByClassName()
Use case Single element Group of elements

👉 Rule of thumb

  • Use id for unique elements

  • Use class for repeated styling


 7. Naming Rules & Best Practices

✔ Must be unique
✔ Case-sensitive
✔ No spaces (use - or _)
✔ Start with a letter

Good

<div id="main-content"></div>

Bad ❌

<div id="Main Content"></div>
<div id="123box"></div>

❌ Common Mistakes

❌ Using same id on multiple elements
❌ Confusing id with class
❌ Forgetting # in CSS
❌ Overusing id for styling instead of class


🧠 Key Points to Remember

  • id uniquely identifies one element

  • Selected using # in CSS

  • Used heavily in JavaScript

  • Ideal for anchors & unique layout parts

  • Never repeat the same id

You may also like...