References

Beginner-friendly references for web development, with live, editable examples.

The CSS #id selector

Selector CSS All modern browsers Updated
Quick answer

The CSS ID selector targets the single element with a given id, written with a hash — #header { … } styles the element with id="header". An ID should be unique on the page. Its specificity is very high and hard to override, so for styling most developers prefer classes.

Overview

The ID selector matches one element — the one with a matching id attribute — using a hash: #main { … }. Because an id must be unique within a page, an ID selector is for that single, specific element, not a group.

It works, but it comes with a catch: very high specificity (1,0,0). An ID selector beats any number of class selectors, which makes its styles stubborn to override and tends to start specificity wars that end in !important. For that reason the common guidance is to avoid IDs for styling and lean on classes instead, which stay flexible.

IDs are still genuinely useful — just for other jobs. They are the target of in-page anchor links (href="#section"), the hook that label for="" and ARIA attributes like aria-labelledby point at, and a fast handle for JavaScript. Use IDs for those roles, and style with classes.

Syntax

/* matches the single id="header" */
#header {
  position: sticky;
  top: 0;
}

Example

Live example
<style>
  #hero {
    background: #1c7ce9;
    color: #fff;
    padding: 22px;
    border-radius: 10px;
    text-align: center;
    font: 700 18px system-ui, sans-serif;
  }
</style>
<div id="hero">Styled with #hero (one unique element)</div>

Best practices

  • Prefer classes for styling; reserve IDs for anchors, form labels, ARIA references and JavaScript hooks.
  • Keep every id unique on the page — duplicate IDs are invalid and break label and anchor behavior.
  • Be aware an ID selector's high specificity makes its styles hard to override; that is the main reason to avoid it in CSS.
  • If you must override an ID-based style, you generally need another ID or !important — a sign to refactor toward classes.

Frequently asked questions

How do I select an ID in CSS?
Use a hash before the name, e.g. #header { … } styles the element with id="header".
Should I use IDs or classes for styling?
Classes. IDs have very high specificity that is hard to override. Use IDs for anchors, labels and JavaScript hooks, and style with classes.
Can I use the same ID on more than one element?
No. An id must be unique per page. Duplicates are invalid and break anchor links, label for and ARIA references.
Why is my ID style so hard to override?
Because an ID selector has high specificity (1,0,0) — it beats class and element selectors. Refactor to a class so the style stays easy to override.