0
0
HTMLmarkup~5 mins

ID attribute in HTML

Choose your learning style9 modes available
Introduction

The ID attribute gives a unique name to an HTML element. It helps you find and style that element easily.

When you want to style one specific element differently from others.
When you want to link to a specific part of a page using a URL.
When you want to select an element in JavaScript to change or read it.
When you want to improve accessibility by labeling elements uniquely.
When you want to create a navigation menu that jumps to sections on the same page.
Syntax
HTML
<tag id="uniqueName">Content</tag>
The id value must be unique on the whole page.
Use only letters, digits, hyphens (-), underscores (_), colons (:), and periods (.) in the id.
Examples
A div element with the ID 'header' to identify the top section.
HTML
<div id="header">Welcome</div>
A paragraph with a unique ID 'intro' for styling or scripting.
HTML
<p id="intro">This is the introduction paragraph.</p>
A section with ID 'contact' to link or style the contact area.
HTML
<section id="contact">Contact us here.</section>
Sample Program

This page shows three paragraphs. Only the one with the ID highlight has a yellow background and orange border. The ID lets CSS style just that paragraph.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ID Attribute Example</title>
  <style>
    #highlight {
      background-color: lightyellow;
      border: 2px solid orange;
      padding: 1rem;
      max-width: 20rem;
      margin: 1rem auto;
      font-family: Arial, sans-serif;
      text-align: center;
    }
  </style>
</head>
<body>
  <h1 id="main-title">Welcome to My Page</h1>
  <p>This paragraph is normal.</p>
  <p id="highlight">This paragraph is special because it has an ID.</p>
  <p>Another normal paragraph.</p>
</body>
</html>
OutputSuccess
Important Notes

Remember, each ID must be unique on the page. Using the same ID twice can cause confusion in styling and scripting.

IDs are case-sensitive. Header and header are different.

Use IDs to improve keyboard navigation and screen reader support by linking labels and controls.

Summary

The ID attribute names one unique element on the page.

Use it to style, link, or script that element easily.

Always keep IDs unique and simple.