Skip to main content

CSS Selectors

CSS ID Selector

Written by Updated CSS ID Selector exercises

Understand how ID selectors target unique elements, why their high specificity is difficult to override, and when another selector is preferable.

The ID selector styles one single element: the one with that id. Write #header in CSS and it matches the element with id="header", and nothing else.

An ID must be unique on the page, which is the main difference from the class selector: a class can be on many elements, an ID on only one.

ID Selector Syntax

css

#idname {
    property: value;
}

ID Selector Example

css

#header {
    color: blue;
    text-align: center;
}

The matching HTML

html

<h1 id="header">My website</h1>

That heading turns blue and centered.

Example

CSS ID Selector Complete Example

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS ID Selector</title>
    <style>
        #header {
            color: blue;
            text-align: center;
        }

        #box {
            background: lightgray;
            padding: 10px;
            border: 1px solid black;
        }
    </style>
</head>
<body>

    <h1 id="header">ID Selector Example</h1>

    <p>This is a normal paragraph.</p>

    <div id="box">This is a styled box using ID.</div>

</body>
</html>

The heading with id="header" is blue and centered, the div with its own ID gets a grey background, padding and a border, and nothing else on the page changes.

Browser Support

Feature
Chrome
Edge
Firefox
Safari
ID selector11211

Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.

Why most developers style with classes, not IDs

IDs are very strong in CSS. In the specificity rules that decide which style wins, one ID beats any number of classes. That sounds useful until you need to change something: to override #header h1, a class is not enough, so you add another ID, and the stylesheet slowly becomes a fight.

So the usual habit is:

  • Use classes for how things look.
  • Use IDs for what makes an element unique: a target for links like href="#contact", connecting a <label for="email"> to its input, or finding the element in JavaScript.

Rules to remember

  • Use each ID only once per page. Browsers will not complain if you repeat it, but links, labels and JavaScript will then find the wrong element.
  • An element can have only one ID, but it can have many classes.
  • IDs are case-sensitive and cannot contain spaces. An ID can technically start with a number, but #2col then needs escaping in CSS, so start with a letter.

CSS ID Selector exercises

An id

Give the element with the id top the background color navy and white text.

The HTML your code works on
<header id="top">Top</header>
<p id="intro" class="text">Intro</p>
<p class="text">More</p>
<section id="main">
  <p>Inside</p>
</section>

Result

Check your answer to see it here.