CSS ID Selector

The CSS ID selector selects an HTML element based on the value of its id attribute. An ID should uniquely identify a single element within a document, making the ID selector useful when a style is intended for one specific element.

Syntax

An ID selector is written with a number sign (#) followed by the ID value:

#id-name {
  property: value;
}

For example, the following selector matches the element with id="notice":

#notice {
  color: #0088cc;
}

How the ID Selector Works

The ID selector matches an element whose id attribute has the specified value. The number sign is part of the CSS selector but is not included in the HTML id attribute.

#featured {
  background-color: #d8f1fc;
  color: #0088cc;
}

The selector #featured matches an element such as:

<div id="featured">Featured content</div>

Using Unique IDs

An id value must be unique within an HTML document. Two elements in the same document should not use the same ID.

<section id="introduction">
  <h2>Introduction</h2>
</section>

The ID can be used by CSS to select the element, but HTML IDs also have other uses, including fragment links, scripting, and associating elements through certain HTML attributes.

Combining with Other Selectors

An ID selector can be combined with other selectors to create a more specific match.

section#introduction {
  background-color: #d8f1fc;
}

This selector matches a <section> element whose ID is introduction.

An ID selector can also be used as part of a descendant or child selector:

#content p {
  line-height: 1.6;
}
#navigation > a {
  color: #0088cc;
}

The first rule selects paragraphs that are descendants of the element with id="content". The second selects links that are children of the element with id="navigation".

Specificity

An ID selector contributes 1-0-0 to a selector's specificity. ID selectors therefore have greater specificity than class, attribute, pseudo-class, and type selectors.

Selector Specificity
#notice 1-0-0
div#notice 1-0-1
#content .notice 1-1-0
#content p.notice 1-1-1

Because an ID selector has high specificity, declarations using IDs can require selectors with equal or greater specificity to override them when the competing declarations otherwise have the same cascade precedence.

ID Selector Example

The following example uses the #featured ID selector to style one element. The second element has no matching ID and is not affected by the rule.

#featured {
  background-color: #d8f1fc;
  color: #0088cc;
  font-weight: 600;
}

Play in Editor

Other basic selectors can select elements by element name, class, or without restricting the element type:

Specifications

The ID selector is defined in the Selectors Level 4 specification.