With the #id selector in CSS, you can select and style an HTML element based on the value of its id attribute.
The id attribute must be unique in your HTML document. If multiple DOM elements have the same id, the browser will apply the style only to the first DOM element that matches the pattern.
Read below for a real-world example of using the #id selector in your CSS style sheets.
How to Use the Id Selector in CSS
Say you have the following HTML document:
<!-- Regular paragraph -->
<p>This is a regular paragraph.</p>
<!-- Special paragraph -->
<p id="special-paragraph">This is a paragraph with its own id.</p>
As you can see from the source code above, there are two paragraphs in your HTML document.
One paragraph is in a regular <p>
tag, and the other in a <p>
tag with an id of special-paragraph
. You can style the second paragraph using the #id selector in CSS.
#special-paragraph {
color: blue;
}
The #id selector in CSS is supported by all major browsers, including, but not limited to, Google Chrome, Firefox, Microsoft Edge, Safari, and Opera. (For detailed information on browser support, refer to the #id selector specs at CanIUse.com.)
Keep learning: The Simple Guide to Complex CSS Selectors