Chapter 03 of 33

CSS Selectors

Every CSS rule starts with a selector. Before the browser can make something red or bold, it needs to know which elements you are talking about: all paragraphs? Only the warning message? Only the main heading?

In this chapter we learn the basic selectors that you will use in almost every line of CSS you write: the universal, type, class and ID selectors, plus how to group and combine them. The more advanced ones — combinators, attribute selectors, pseudo-classes and pseudo-elements — follow in the next two chapters.


What is a Selector?

A selector is a pattern that matches elements in the document tree. The declarations in a rule are applied to every element the selector matches.

p {
  color: gray;
}

Here p is the selector. The browser walks through the page, and every element that matches the pattern p (every paragraph) gets color: gray.

We'll use this HTML for the examples in this chapter:

<h1 id="main-title">CSS Selectors</h1>
<h2>Subheading</h2>
<p>Normal paragraph.</p>
<p class="highlight">Highlighted paragraph.</p>
<p class="highlight important">Highlighted and important.</p>
<span class="highlight">A highlighted span.</span>
<div class="card">Plain card</div>
<div class="card featured">Featured card</div>
<div class="featured">Only featured</div>

1. The Universal Selector (*)

The asterisk * matches every element.

* {
  box-sizing: border-box;
}

This applies box-sizing: border-box to all elements — a very common line at the top of style sheets (you will understand why in The Box Model).

Use it carefully. Something like * { color: red; } would hit every single element, overriding inherited colours everywhere. The universal selector is mostly used for resets, or as part of larger selectors (for example .card * = every element inside a card).


2. Type Selector (Element Selector)

A type selector is just an HTML element name. It matches all elements of that type.

p {
  color: #444444;
}

h2 {
  font-size: 24px;
}

Every paragraph and every h2 on the page is affected; elements of other types are not.

  • Type selectors are good for base styles: the default look of all paragraphs, links, tables, etc.

  • In HTML documents they are case-insensitive (P works like p), but always write lowercase.


3. Class Selector (.)

A class selector starts with a dot and matches every element whose class attribute contains that class name.

.highlight {
  background-color: yellow;
}

Output: the two paragraphs and the <span> with class highlight get a yellow background. The class selector does not care about the element type.

Multiple classes on one element

An element can have several classes, separated by spaces:

<p class="highlight important">Highlighted and important.</p>
.highlight {
  background-color: yellow;
}

.important {
  font-weight: bold;
}

This paragraph matches both rules, so it is yellow and bold. This is the core idea of reusable CSS: small classes that can be mixed and matched.

Why classes are the workhorse of CSS

  • They are reusable: any number of elements can share a class.

  • They describe a role rather than an element type, so you can change <div class="card"> to <article class="card"> without touching the CSS.

  • They have a moderate, predictable specificity (more on that below).

Most professional CSS — including methodologies like BEM (see CSS Architecture & BEM) — is written mainly with class selectors.


4. ID Selector (#)

An ID selector starts with # and matches the element whose id attribute equals that name.

#main-title {
  color: darkblue;
}

Output: only the <h1 id="main-title"> turns dark blue.

Rules about IDs:

  • An id must be unique in the page. If you duplicate it, browsers will still style both elements, but the HTML is invalid and JavaScript's getElementById will only find the first one.

  • An element can have only one id (but many classes).

  • IDs are also used for in-page links (<a href="#main-title">), form labels and JavaScript.

Why many developers avoid ID selectors for styling

An ID selector is far "stronger" than a class selector in the cascade. Once you style something with an ID, overriding it later requires another ID or worse. It also can't be reused. The common practice is: use IDs for linking and JavaScript, use classes for styling.


Class vs ID

PointClassID
Symbol in CSS.name#name
HTML attributeclass="name"id="name"
How many elements can use it?Any numberExactly one per page
How many per element?Many (space-separated)One
Specificity weightMediumHigh
Typical useStyling reusable componentsUnique landmarks, anchors, JavaScript hooks

5. Grouping Selectors (,)

When several selectors need the same declarations, list them separated by commas. This is called a selector list.

/* Without grouping: repetitive */
h1 { font-family: Georgia, serif; }
h2 { font-family: Georgia, serif; }
h3 { font-family: Georgia, serif; }

/* With grouping: one rule */
h1, h2, h3 {
  font-family: Georgia, serif;
}

Both versions produce the same result. Grouping keeps the CSS short and makes sure the shared style stays consistent.

The comma means "or": the rule applies to an element that is an h1 or an h2 or an h3. Each item in the list is matched independently.

A trap: one invalid selector kills the whole list

h1, h2:hovver {      /* typo: :hovver does not exist */
  color: red;
}

Output: nothing turns red — not even h1. If any selector in a list is invalid, the browser discards the entire rule. Keep risky or very new selectors in their own rule, or use the forgiving :is() function covered in Pseudo-classes & Pseudo-elements.


6. Compound Selectors (Combining Without Spaces)

You can join simple selectors without any space to require that the same element matches all of them. This is a compound selector.

Element + class

p.highlight {
  border: 2px solid orange;
}

This means: "an element that is a p and has class highlight". The two highlighted paragraphs get an orange border; the highlighted <span> does not, because it is not a p.

Two classes together

.card.featured {
  border: 3px solid green;
  padding: 8px;
}

Output, step by step:

ElementHas card?Has featured?Matches .card.featured?
<div class="card">YesNoNo
<div class="card featured">YesYesYes — green border
<div class="featured">NoYesNo

The order of classes doesn't matter: .featured.card means the same thing, and class="featured card" matches too.

Space vs no space — the most important detail

SelectorMeaning
p.highlightA p that itself has class highlight
p .highlightAn element with class highlight somewhere inside a p
p, .highlightEvery p, and also every element with class highlight

One space completely changes the meaning. The space is the descendant combinator, which we study in Combinators & Attribute Selectors.

In a compound selector, the type selector (if any) must come first: p.highlight is valid, .highlightp would be read as a single class named highlightp.


The Complete Example

Putting it all together:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Selectors Demo</title>
  <style>
    * { box-sizing: border-box; }
    body { font-family: Arial, sans-serif; }
    p { color: #444444; }
    .highlight { background-color: yellow; }
    .important { font-weight: bold; }
    #main-title { color: darkblue; }
    p.highlight { border: 2px solid orange; }
    h1, h2, h3 { font-family: Georgia, serif; }
    .card.featured { border: 3px solid green; padding: 8px; }
  </style>
</head>
<body>
  <h1 id="main-title">CSS Selectors</h1>
  <h2>Subheading</h2>
  <p>Normal paragraph.</p>
  <p class="highlight">Highlighted paragraph.</p>
  <p class="highlight important">Highlighted and important.</p>
  <span class="highlight">A highlighted span.</span>
  <div class="card">Plain card</div>
  <div class="card featured">Featured card</div>
  <div class="featured">Only featured</div>
</body>
</html>

Output:

CSS Selectors              ← dark blue, Georgia (id + group)
Subheading                 ← black, Georgia (group)
Normal paragraph.          ← grey
Highlighted paragraph.     ← grey on yellow, orange border
Highlighted and important. ← grey on yellow, orange border, bold
A highlighted span.        ← yellow background only, no border
Plain card                 ← unstyled
Featured card              ← green border, 8px padding
Only featured              ← unstyled

Naming Classes and IDs

  • Names are case-sensitive: .Note does not match class="note".

  • Use letters, digits, hyphens and underscores. A name must not start with a digit in CSS: .2col is invalid (it would have to be escaped as .\32 col). Just avoid it — use .two-col.

  • Name things by purpose, not by appearance: .error-message stays correct if the design changes from red to orange; .red-text does not.

  • The common convention is lowercase words joined by hyphens (kebab-case): .nav-link, .product-card.


A First Look at Selector Strength

What if an element matches two rules that set the same property differently?

#main-title { color: darkblue; }
h1          { color: red; }

The heading stays dark blue, even though the h1 rule comes later. Selectors have a "weight" called specificity, and a more specific selector beats a less specific one regardless of order:

Selector typeRelative weight
ID (#main-title)Highest
Class (.highlight)Medium
Type (h1)Low
Universal (*)Zero

Only when the specificity is equal does the later rule win. The exact calculation (and why one ID beats any number of classes) is in Specificity, Inheritance & the Cascade.


Common Mistakes

  • Forgetting the dot or hash: highlight { ... } looks for a non-existent <highlight> element.

  • Putting the dot in the HTML: class=".highlight" is wrong; write class="highlight".

  • Using commas in the class attribute: class="highlight, important" creates a class literally named highlight,. Separate classes with spaces only.

  • Accidental spaces: .card .featured (descendant) instead of .card.featured (same element).

  • Reusing an ID for several elements instead of using a class.

  • One typo in a selector list silently disabling the whole rule.


Interview / Exam Questions

1. What is the difference between a class selector and an ID selector?

A class selector (.name) matches every element with that class and can be reused; an element can have many classes. An ID selector (#name) matches the single element with that unique id; an element has at most one id. ID selectors have much higher specificity than class selectors.

2. What does div.box mean? How is it different from div .box?

div.box matches a div element that itself has class box. div .box (with a space) matches any element with class box that is a descendant of a div.

3. Which elements does .btn.primary match: class="btn", class="primary btn", class="btn-primary"?

Only class="primary btn". The element must have both classes (order doesn't matter). btn-primary is a single, different class name.

4. What happens to the rule "h1, p, .x::nonsense { color: red; }"?

The whole rule is dropped because one selector in the list is invalid. Neither h1 nor p becomes red.

5. Write a single rule that makes all h1, h2 and elements with class title use the font Georgia.
h1, h2, .title {
  font-family: Georgia, serif;
}
6. Why is * { margin: 0; padding: 0; } used, and what is its drawback?

It removes the browser's default margins and padding on all elements so that layout starts from a clean, consistent base. The drawback is that it also removes useful defaults (for example list indentation and paragraph spacing), which then have to be added back deliberately.


Summary

SelectorSyntaxMatches
Universal*Every element
TypepAll elements of that type
Class.highlightAll elements with that class
ID#main-titleThe one element with that id
Selector listh1, h2Elements matching any item
Compoundp.highlight, .a.bElements matching all parts at once
  • Prefer classes for styling; keep IDs for anchors and scripts.

  • No space = same element; space = descendant; comma = "or".

  • An invalid selector in a list drops the entire rule.

In the next chapter, Combinators & Attribute Selectors, we will select elements based on their position in the HTML tree and on their attributes.