Definition and Usage
The #id selector
selects elements with an id attribute that matches the specified id value.
It is case-sensitive.
Placing the id value immediately after the # symbol selects elements whose id attribute matches that value.
For example, the #chapter selector matches elements that have an id attribute whose value is chapter.
Basic Example
#chapter { /* Selects the element with id="chapter" */
background-color: darkblue;
color: white;
}
<p id="chapter">The id value is "chapter".</p>
<p>This is just a paragraph element.</p>
Code Explanation
The id attribute specifies a unique identifier (ID) for an element.
The value of this attribute must be unique and distinct within the document (web page).
The id value is "chapter".
This is just a paragraph element.
Syntax
#id_value {
/* ... */
}
The #id_value syntax above selects the same elements as [id="id_value"].
Additional Explanation
The [attribute="value"] selector selects all elements that have a specified attribute whose value exactly matches the specified value.
[id="id_value"] {
/* ... */
}
Although the #id_value and [id="id_value"] selectors match the same elements,
the #id_value selector has a higher specificity value (also known as 'specificity') that determines style precedence than the [id="id_value"] selector.
When the same elements are selected by both the #id_value and [id="id_value"] selectors simultaneously, the styles specified by the #id_value selector, which has a higher style precedence, are applied.
#chapter { /* The specificity value: 0, 1, 0, 0 */
background-color: orange; /* This style is applied. */
}
[id="chapter"] { /* The specificity value: 0, 0, 1, 0 */
background-color: green;
}
<p id="chapter">The id value is "chapter".</p>
The id value is "chapter".
Things to Keep in Mind - High Specificity of the #id Selector
The #id selector has a very high specificity value.
Therefore, overusing the #id selector increases the likelihood of conflicts with other selectors that select the same elements.
Consequently, unless you specifically need higher specificity, it is better to use other selectors with lower specificity instead of the #id selector for easier maintenance.
Specifications
| Specification | |
|---|---|
#id_value
|
Selectors Level 4 #id-selectors |
Browser Compatibility
| Selector |
Desktop Chrome
|
Desktop Edge
|
Desktop Firefox
|
Safari
|
|---|---|---|---|---|
#id_value
|
1 | 12 | 1 | 1 |