What is a selector in CSS? What are selectors used for?
A selector in CSS is the part of a rule that specifies which HTML elements the styles should apply to. Selectors let you pick a single element, a group of elements, or elements based on certain conditions (class, id, tag, state, and so on).
What selectors are used for
- to find the elements you need on the page
- to give them styling
- to control the appearance of different elements in different states (hover, active, focus, and others)
- to describe styles in a structured way, separating presentation from HTML
Examples of basic selectors
| Selector | What it selects | Example |
|---|---|---|
| by tag | elements of a specific tag | p { color: red; } |
| by class | elements with a class | .title { font-size: 20px; } |
| by id | the element with a specific id | #header { background: black; } |
Example of a CSS rule with a selector
css
p {
color: blue;
}Here, p is the selector, and the rule will apply to all <p> tags on the page.
Summary: a selector is a mechanism that lets you pick HTML elements and apply CSS styles to them. Selectors are the foundation of CSS, because they are what determines what style rules apply to.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.