{"id":14204,"date":"2011-09-06T20:07:18","date_gmt":"2011-09-07T03:07:18","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=14204"},"modified":"2013-04-03T13:57:43","modified_gmt":"2013-04-03T20:57:43","slug":"id","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/selectors\/i\/id\/","title":{"rendered":"ID"},"content":{"rendered":"

The #id<\/code> selector allows you to target an element by referencing the id<\/code> HTML attribute. Similar to how class attributes are denoted in CSS with a \u201cperiod\u201d (.<\/code>) before the class name, ID attributes are prefixed with an \u201coctothorpe\u201d (#<\/code>), more commonly known as a \u201chash\u201d or \u201cpound sign\u201d.<\/p>\n

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

ID attribute values should be unique. HTML with two or more identical id<\/code>s 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.<\/p>\n

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

<\/code>Check out this Pen!<\/a><\/pre>\n

A paragraph with both an ID and class attribute is being given contradicting CSS rules; even though the class selector (.reusable<\/code>) is below the ID selector (#unique<\/code>) in the CSS (it would generally overrides styles above it in the \u201ccascade\u201d<\/a>), the paragraph stays red because #unique<\/code> overwhelms the blue color being set by .reusable<\/code>. 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).<\/p>\n

High specificity and uniqueness mean using #id<\/code> is a CSS \u201cnuclear option\u201d: over-powered, inflexible and disproportionately effective. Avoiding the #id<\/code> selector in CSS is considered<\/a> a best<\/a> practice<\/a>: it is preferable<\/a> to use a class in nearly<\/a> every case.<\/p>\n

That being said, ID attributes have several valuable uses outside of CSS:<\/p>\n