HTML id Attribute

Subject: html

๐Ÿ”– HTML id Attribute

The id attribute in HTML is used to assign a unique identifier to a specific element on the webpage. Unlike classes, which can be shared by multiple elements, an id must be unique across the entire HTML document.


โ“ What Is an ID?

You can assign an ID using the id attribute like this:

This unique name can be referenced in CSS, JavaScript, or page anchors.


๐Ÿš€ Why Use IDs?

  • ๐ŸŽฏ Apply CSS styles to a single, unique element
  • ๐Ÿงช Target a specific element with JavaScript
  • ๐Ÿ”— Create anchor links within a page
  • โ™ฟ Enhance accessibility by associating labels with elements

๐Ÿ’ก Example: ID with CSS


๐Ÿ“Œ Key Points About IDs

  • ๐Ÿ”’ IDs must be unique โ€” one per document
  • #๏ธโƒฃ Target with # in CSS (e.g., #main-header)
  • ๐Ÿ” Higher specificity than classes in CSS
  • ๐Ÿง  Ideal for JavaScript DOM manipulation
  • ๐Ÿงผ Use clear, descriptive ID names (e.g., #footer-logo)

๐Ÿง  Key Takeaway

  • The id attribute uniquely identifies a single element
  • Used in CSS (#idName), JavaScript (getElementById()), and anchor links (#idName)
  • Always ensure IDs are unique on the page
  • Prefer IDs for specific targeting, not general styling
  • Combine with semantic HTML for clear and accessible web structure