CSS ID Selector

The CSS ID Selector selects an HTML element using its unique id attribute. It allows you to apply specific styles to one particular element on a webpage.

An ID selector begins with a hash symbol (#) followed by the element’s ID name. Unlike a class, an ID should be unique within an HTML document.

CSS ID Selector Syntax

The syntax for an ID selector is:

#idname {
    property: value;
}

For example, #header selects the element with id="header".

CSS ID Selector Example

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

        #intro {
            font-size: 18px;
            color: green;
        }
    </style>
</head>
<body>
    <h1 id="main-heading">Welcome to Web4Learners</h1>
    <p id="intro">Learn CSS step by step.</p>
    <p>This paragraph uses the default styling.</p>
</body>
</html>

In this example, the #main-heading selector styles the heading in blue and centers it. The #intro selector changes the first paragraph’s text color and font size.

Using an ID Selector with HTML

First, assign an ID to an HTML element. Then use the same ID in your CSS, preceded by #.

<h2 id="about">About Us</h2>
#about {
    color: darkblue;
    font-size: 26px;
}

The CSS rule applies to the element with id="about".

You can learn more about assigning IDs in our HTML ID Attribute tutorial.

CSS ID Selector vs. Class Selector

An ID selector targets an element by its ID, while a class selector targets elements sharing a class name.

FeatureID SelectorClass Selector
Symbol#.
Example#header.header
Intended useOne unique elementOne or more elements
SpecificityHigherLower

For example, #header has higher specificity than .header. Learn more in our CSS Specificity tutorial.

When to Use CSS ID Selectors

Use ID selectors when you need to style a specific element, such as a main heading or a unique page section. For reusable styles shared by multiple elements, class selectors are generally more suitable.

Explore our CSS Class Selector tutorial to learn how to apply styles to multiple elements.