CSS: CSS Selectors
Selectors are the core of CSS — their job is to "select" the HTML elements you want to style. CSS offers multiple types of selectors, from simple tag selectors to complex selector combinations, giving you precise control over any element.
1. Basic Selectors
(1) Tag Selector (Element Selector)
Uses HTML tag names directly as selectors, matching all tags with the same name in the document.
/* All <p> elements turn red */
p {
/* Text color */
/* Text color */
/* Text color */
/* Text color */
color: red;
}
/* All <h1> elements turn blue */
h1 {
/* Text color */
/* Text color */
/* Text color */
/* Text color */
color: blue;
}
/* All <div> elements get a border */
div {
/* Box model properties */
/* Box model properties */
/* Box model properties */
/* Box model properties */
border: 1px solid black;
}
(2) Class Selector
Matches elements by their class attribute. Class names are prefixed with a period ..
/* All elements with class="highlight" */
.highlight {
/* Background style */
/* Background style */
/* Background style */
/* Background style */
background-color: yellow;
}
/* Only <p> elements with class="center" */
p.center {
/* Font style */
/* Font style */
/* Font style */
/* Font style */
text-align: center;
}
HTML elements can have multiple classes, separated by spaces:
<!-- Paragraph -->
<!-- Paragraph -->
<!-- Paragraph -->
<!-- Paragraph -->
<p class="highlight center">This text is both highlighted and centered</p>
(3) ID Selector
Matches elements by their id attribute, prefixed with a hash #.
/* Select element with id="header" */
#header {
/* Background style */
/* Background style */
/* Background style */
/* Background style */
background-color: #333;
/* Text color */
/* Text color */
/* Text color */
/* Text color */
color: white;
}
Note: An ID can only appear once per page. ID selectors are typically used for unique elements.
(4) Universal Selector
Uses an asterisk * to match all elements in the document.
/* Reset margins and padding for all elements */
* {
/* Box model properties */
/* Box model properties */
/* Box model properties */
/* Box model properties */
margin: 0;
/* Box model properties */
/* Box model properties */
/* Box model properties */
/* Box model properties */
padding: 0;
}
The universal selector is convenient, but be careful about performance — if complex styles are applied, it can affect page rendering speed.
▶ Example
Targeting elements with attribute selectors:
▶ Try it Yourself2. Selector Specificity
When multiple selectors apply to the same element, the browser uses specificity rules to determine which style takes effect:
| Selector Type | Specificity Value |
|---|---|
| Inline styles (style attribute) | 1000 |
| ID selectors | 0100 |
| Class/Attribute/Pseudo-class selectors | 0010 |
| Tag/Pseudo-element selectors | 0001 |
| Universal selector | 0000 |
Priority from high to low:
Inline styles > ID selectors > Class selectors > Tag selectors
(1) Specificity Calculation Example
/* Specificity: 0001 */
p {
/* Text color */
/* Text color */
/* Text color */
/* Text color */
color: black;
}
/* Specificity: 0010 */
.text {
/* Text color */
/* Text color */
/* Text color */
/* Text color */
color: blue;
}
/* Specificity: 0100 */
#special {
/* Text color */
/* Text color */
/* Text color */
/* Text color */
color: green;
}
/* Specificity: 0011 (class + tag) */
p.text {
/* Text color */
/* Text color */
/* Text color */
/* Text color */
color: red;
}
For the same <p class="text" id="special"> element, the final text color will be green (ID selector has the highest specificity).
(2) !important
CSS provides a "nuclear weapon" — !important — that forces a style to have the highest priority:
p {
/* Text color */
/* Text color */
/* Text color */
/* Text color */
color: red !important;
}
Don't use !important unless absolutely necessary — it makes style debugging difficult. Prioritize solving problems by increasing selector specificity.
▶ Example
Specificity showdown — which rule wins:
▶ Try it YourselfThe text renders green — the ID selector in #main .text gives it the highest specificity.
3. Best Practices for Selectors
- Use class selectors frequently: Classes are reusable and the most flexible selector
- Use ID selectors sparingly: IDs are unique, hard to reuse, and their high specificity can cause override issues
- Avoid over-specification:
div.container ul li ais too specific;.nav-linkis enough - Keep selectors concise: Longer selectors are harder to maintain and affect performance
▶ Example
A complete example combining element, class, and ID selectors:
▶ Try it YourselfThe browser applies each rule to the matching element: h1 is navy, the highlighted paragraph has a yellow background, and the unique element is bold.
❓ FAQ
p targets every paragraph, .card targets every element with class="card", #header targets the one element with id="header". The browser finds the matching elements first, then applies the properties inside { } one by one..card and ids need #header, a bare card looks for a <card> tag; the name in the HTML is misspelled; your rule loses the specificity battle and gets overridden; the stylesheet never loaded; or a typo in a pseudo-class (:hover written as :hove). Open DevTools, search for your selector, and check whether the rule even shows up in the Styles panel.class="card" in HTML and .card { padding: 20px; } in CSS — note the dot before the name. One element can carry several classes: class="card featured" (space-separated). A class can be reused as many times as you want — that's the biggest difference from id, and why classes are the default choice in real projects.id="top-bar" in HTML and #top-bar { height: 60px; } in CSS — hash sign in front. An id must be unique on the page, so it can't be reused. Its specificity is also high (100): if some style refuses to be overridden, check whether the winner's selector contains an id.#nav .item (110) beats .nav .item (20). Equal weight goes to whichever rule is written later. !important doesn't take part in the math — it jumps straight to the top..card .title outweighs a bare .title), repeat the same class (.title.title doubles it), or switch to an id. !important is the last resort — it makes future maintenance harder, and in one project you should be able to count its uses on one hand.div p selects all p elements inside div at any level, while div > p only selects direct child p elements, regardless of grandchildren.* matches all elements, the browser checks each one. If nested in complex selectors (like #nav * li), it may cause performance waste. Simple global resets like * { box-sizing: border-box; } are fine.📖 Summary
- Selectors are the fundamental CSS skill — mastering tag, class, and ID selectors covers most styling needs
- Understanding selector specificity helps avoid confusion about "why isn't my style working"
- In practice, class selectors are used most frequently — prefer class-based styling
📝 Exercises
- Create an HTML page with headings, paragraphs, and lists.
- Use tag selectors to set text color for all paragraphs.
- Use class selectors to set different background colors for specific elements (define at least 2 different classes).
- Use ID selectors to set special styles for one element on the page.
- Test: Apply tag, class, and ID selectors to the same element and observe which has the highest priority.