0
0
CssHow-ToBeginner · 3 min read

How to Use ID Selector in CSS: Syntax and Examples

Use the # symbol followed by the element's unique id to select it in CSS. For example, #header { color: blue; } styles the element with id="header". The id selector targets exactly one element on the page.
📐

Syntax

The id selector in CSS uses the # symbol followed by the unique id attribute value of an HTML element.

  • #idName: Selects the element with id="idName".
  • The id must be unique on the page.
  • Use curly braces { } to define styles for that element.
css
#elementId {
  property: value;
}
💻

Example

This example shows how to style a heading with the id title to have red text and a larger font size.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ID Selector Example</title>
  <style>
    #title {
      color: red;
      font-size: 2rem;
      text-align: center;
    }
  </style>
</head>
<body>
  <h1 id="title">Welcome to My Website</h1>
  <p>This paragraph is not styled by the id selector.</p>
</body>
</html>
Output
A centered large heading in red text that says 'Welcome to My Website' and a normal paragraph below it.
⚠️

Common Pitfalls

Common mistakes when using the id selector include:

  • Using the same id on multiple elements, which breaks uniqueness and causes unexpected styling.
  • Forgetting the # symbol in CSS, which makes the selector invalid.
  • Confusing id selectors with class selectors (which use .).
css
/* Wrong: missing # */
title {
  color: blue;
}

/* Right: with # */
#title {
  color: blue;
}

/* Wrong: duplicate ids in HTML */
<!-- <h1 id="header">First</h1> -->
<!-- <h2 id="header">Second</h2> -->

/* Right: unique ids */
<!-- <h1 id="header1">First</h1> -->
<!-- <h2 id="header2">Second</h2> -->
📊

Quick Reference

  • Selector: #idName
  • Targets: One unique element with that id
  • Use: Styling or scripting a specific element
  • Note: id must be unique per page

Key Takeaways

Use #id to select a unique element by its id in CSS.
The id attribute must be unique on the page to avoid conflicts.
Always include the # symbol before the id name in CSS selectors.
Id selectors have higher priority than class selectors in CSS.
Use id selectors for styling or scripting specific single elements.