ID

Avatar of Sara Cope
Sara Cope on (Updated on )

The #id selector allows you to target an element by referencing the id HTML attribute. Similar to how class attributes are denoted in CSS with a “period” (.) before the class name, ID attributes are prefixed with an “octothorpe” (#), more commonly known as a “hash” or “pound sign”.

<header id="site-header"></header>
#header { /* this is the ID selector */
  background: #eee;
}

ID attribute values should be unique. HTML with two or more identical ids does not validate, and will produce unpredictable results. If there are two of the same, CSS will still match and style both. JavaScript however, when querying for an ID, will find the first and stop.

ID selectors are extremely powerful. They have a very high specificity, generally written as (0, 1, 0, 0). Styles applies with them override other selectors that only use tags or classes. To demonstrate:

Check out this Pen!

A paragraph with both an ID and class attribute is being given contradicting CSS rules; even though the class selector (.reusable) is below the ID selector (#unique) in the CSS (it would generally overrides styles above it in the “cascade”), the paragraph stays red because #unique overwhelms the blue color being set by .reusable. An infinite amount of classes can never beat the specificity of the ID (although there was a bug at one time where 256 classes would beat an ID).

High specificity and uniqueness mean using #id is a CSS “nuclear option”: over-powered, inflexible and disproportionately effective. Avoiding the #id selector in CSS is considered a best practice: it is preferable to use a class in nearly every case.

That being said, ID attributes have several valuable uses outside of CSS:

  • Providing unique hooks for JavaScript
  • Elements with id attributes can be targeted by anchor tags, by setting the href attribute to the id value, prefixed by a # symbol. Clicking that anchor link will re-focus the current page on the element with the matching id. This is called a “fragment identifier”.
  • For truly unique elements in your HTML, such as form elements, IDs could be useful for things like linking labels and inputs.

Points of Interest

  • A valid #id cannot start with a number and must be at least one character long. A large part of the Unicode are valid characters in an id.
  • id attributes and selectors are case-sensitive, and must exactly match across HTML, CSS and JavaScript

Other Resources

Browser Support

Chrome Safari Firefox Opera IE Android iOS
Any Any Any Any Any Any Any