To write an ID selector in CSS, you use a hashtag (#) followed by the ID of the HTML element you want to style. This selects a single, unique element on the page.
Explanation and Example
The ID selector is a powerful tool in CSS because it targets a specific element. Each element on a webpage should only have one unique ID. This makes ID selectors perfect for styling specific, important elements like headers, footers, or main content sections.
Here's a breakdown:
-
HTML: You need an HTML element with an
id
attribute. For example:<div id="main-content"> <p>This is the main content of the page.</p> </div>
-
CSS: In your CSS, use the hashtag (#) followed by the ID name (
main-content
in this case) to select and style the element.#main-content { background-color: #f0f0f0; padding: 20px; border: 1px solid #ccc; }
In this example, the CSS will style the div
with the ID main-content
by giving it a light gray background, padding, and a gray border.
Syntax Summary
Selector | Description | Example |
---|---|---|
#id |
Selects the element with id=id | #main-content |
Important Considerations
- Uniqueness: IDs should be unique on a page. Avoid using the same ID for multiple elements. If you need to style multiple elements the same way, use classes instead.
- Specificity: ID selectors are very specific. They generally override class selectors. This can be useful, but it can also make your CSS harder to maintain if you overuse IDs for styling.
In short, to style an element by its ID, use the hashtag (#) followed by the ID name in your CSS. This selects the single, unique element on your page with that ID.