Chapter 04 of 33

Combinators & Attribute Selectors

In CSS Selectors we targeted elements by their type, class and ID. That is enough for simple pages, but real pages raise questions like: "style only the links inside the navigation bar", "style the paragraph that comes right after a heading", or "style every link that points to a PDF file".

For these we need two new tools:

  • Combinators — select elements based on their relationship with other elements in the HTML tree.

  • Attribute selectors — select elements based on their attributes and attribute values.


Thinking of HTML as a Tree

Combinators only make sense once you picture the document as a family tree. Consider:

<div class="article">
  <p>P1</p>
  <section>
    <p>P2</p>
  </section>
  <h2>Heading</h2>
  <p>P3</p>
  <p>P4</p>
</div>
<p>P5</p>
            (body)
           /      \
   div.article     P5
   /   |    \   \    \
 P1 section  h2  P3   P4
       |
       P2
TermMeaningExample from the tree
ParentThe element directly containing anothersection is the parent of P2
ChildAn element directly inside another (one level down)P1, section, h2, P3, P4 are children of div.article
DescendantAny element inside another, at any depthP1, P2, P3, P4 are all descendants of div.article
SiblingsElements with the same parenth2, P3 and P4 are siblings
Next siblingThe sibling immediately afterP3 is the next sibling of h2

We'll use this exact HTML to test each combinator.


The Four Combinators

CombinatorSyntaxName (Selectors Level 4)Selects B when...
spaceA BDescendant combinatorB is anywhere inside A
>A > BChild combinatorB is a direct child of A
+A + BNext-sibling combinatorB comes immediately after A, same parent
~A ~ BSubsequent-sibling combinatorB comes anywhere after A, same parent

Older books call + the "adjacent sibling combinator" and ~ the "general sibling combinator" — same things, older names. In every case, the element that gets styled is the one on the right.

1. Descendant combinator (space)

.article p {
  color: blue;
}

"Every p that is somewhere inside .article." Depth doesn't matter.

Output: P1, P2, P3 and P4 turn blue. P2 is included even though it is inside a section. P5 is outside .article, so it is not affected.

This is the most commonly used combinator — for example nav a for all links in the navigation, or footer p for paragraphs in the footer.

2. Child combinator (>)

.article > p {
  font-weight: bold;
}

"Every p whose parent is .article."

Output: P1, P3 and P4 become bold. P2 is not bold, because its parent is section, not .article.

Use > when nested structures repeat. A classic case is a multi-level menu:

/* Only the top-level menu items, not the items of nested sub-menus */
.menu > li {
  display: inline-block;
}

3. Next-sibling combinator (+)

h2 + p {
  background: #ffe08a;
}

"A p that comes immediately after an h2, with the same parent."

Output: only P3 gets the yellow background. P4 is after the h2 too, but not immediately after it.

A practical use is the "lead paragraph" — making the first paragraph after a heading larger — or removing the gap between a heading and the text that follows it.

4. Subsequent-sibling combinator (~)

h2 ~ p {
  border-left: 4px solid green;
  padding-left: 6px;
}

"Every p that comes after an h2 (not necessarily immediately), with the same parent."

Output: P3 and P4 get the green left border. P1 is a sibling but comes before the h2, so it is not selected.

Combined result

Applying all four rules together to our HTML:

P1  → blue, bold
P2  → blue                         (grandchild: not bold)
Heading
P3  → blue, bold, yellow background, green left border
P4  → blue, bold, green left border
P5  → unstyled                     (outside .article)

Combinators Only Look Down and Forward

Notice that every combinator moves either down the tree (descendant, child) or forward among siblings (+, ~). With combinators alone you cannot select:

  • a parent based on its child ("the card that contains an image"), or

  • a previous sibling ("the label before an invalid input").

For many years this was simply impossible in CSS. The :has() pseudo-class (supported in all major browsers since December 2023) now solves it, for example .card:has(img). It is introduced in Pseudo-classes & Pseudo-elements and explored fully in Modern CSS: :has(), Nesting, clamp() & Logical Properties.


Longer Chains and How Browsers Read Them

Combinators can be chained:

nav > ul > li > a {
  text-decoration: none;
}

.sidebar .widget h3 + p {
  margin-top: 0;
}

Read chains from right to left — that is also how browser engines match them. For .sidebar .widget h3 + p the browser asks:

  1. Is this element a p? If not, stop immediately.

  2. Is the sibling just before it an h3?

  3. Does that h3 have an ancestor with class widget?

  4. Does that .widget have an ancestor with class sidebar?

The rightmost part is called the key selector; it filters out most elements quickly. Modern engines are very fast, so you rarely need to worry about selector performance — but long chains have a real cost in maintainability: they break when the HTML structure changes, and they create high specificity. A good guideline is to keep selectors to about three parts or fewer and prefer a well-named class.


Attribute Selectors

Attribute selectors match elements by their HTML attributes. They are written in square brackets.

SelectorMatches elements whose attribute...Example
[attr]exists (any value, even empty)a[target]
[attr="v"]is exactly vinput[type="email"]
[attr~="v"]is a space-separated list containing the word v[class~="btn"]
[attr|="v"]is exactly v or starts with v-[lang|="en"]
[attr^="v"]starts with va[href^="https"]
[attr$="v"]ends with va[href$=".pdf"]
[attr*="v"]contains v anywherea[href*="example"]

Memory aid: ^ means "start" (as in regular expressions), $ means "end", * means "anywhere".

A complete attribute selector example

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Attribute selectors</title>
  <style>
    body { font-family: Arial, sans-serif; }

    a[target] { color: red; }
    a[href^="https"] { text-decoration: underline wavy; }
    a[href$=".pdf"]::after { content: " (PDF)"; }
    a[href*="example"] { font-style: italic; }

    input[type="email"] { border: 2px solid purple; }
    [class~="btn"] { padding: 4px 10px; background: #dddddd; }
    [lang|="en"] { color: teal; }
  </style>
</head>
<body>
  <p>
    <a href="https://example.com" target="_blank">Example</a> |
    <a href="/files/notes.pdf">Notes</a> |
    <a href="/files/SYLLABUS.PDF">Syllabus</a> |
    <a href="http://other.org">Other</a>
  </p>
  <p>
    <input type="email" placeholder="email">
    <input type="text" placeholder="text">
  </p>
  <p>
    <span class="btn primary">btn primary</span>
    <span class="btn-large">btn-large</span>
  </p>
  <p lang="en-IN">lang en-IN</p>
  <p lang="en">lang en</p>
  <p lang="english">lang english</p>
</body>
</html>

Output, explained element by element:

ElementResultWhy
Example linkRed, wavy underline, italicHas target; href starts with https; contains example
Notes linkShows "Notes (PDF)"href ends with .pdf; the ::after pseudo-element inserts the text " (PDF)" after the link's content (pseudo-elements are covered in the next chapter)
Syllabus linkPlain link, no "(PDF)"Values are case-sensitive: .PDF ≠ .pdf
Other linkPlain linkhttp:// does not start with https
Email inputPurple bordertype is exactly email
btn primary spanGrey background, paddingIts class list contains the whole word btn
btn-large spanUnstyledbtn-large is a different word; ~= matches whole words only
lang="en-IN" and lang="en"TealExactly en, or starts with en-
lang="english"BlackStarts with en but not with en-

Case sensitivity and the i flag

As the Syllabus link shows, attribute values are normally compared case-sensitively (a few HTML attributes such as type are an exception and are matched case-insensitively by browsers). To ignore case, add i before the closing bracket:

a[href$=".pdf" i]::after {
  content: " (PDF)";
}

Now both notes.pdf and SYLLABUS.PDF get the label. The i flag works in all modern browsers. There is also an s flag that forces case-sensitive matching, but Chromium-based browsers (Chrome, Edge) still do not support it. There, a selector with the s flag is treated as invalid and the whole rule is dropped — so avoid s for now.

Quotes

Quotes around the value are optional when the value is a simple identifier ([type=email]), but required when it contains spaces, dots, slashes or starts with a digit ([href$=".pdf"]). Always using quotes is the safest habit.

Class selector vs [class=...]

Selectorclass="btn"class="btn primary"
.btnMatchesMatches
[class~="btn"]MatchesMatches
[class="btn"]MatchesNo — the full value is "btn primary"

So .btn is really shorthand for [class~="btn"]. Both have the same specificity: an attribute selector counts the same as a class selector.


Practical Uses of Attribute Selectors

/* Style form controls by type without adding classes */
input[type="text"],
input[type="email"],
input[type="password"] {
  padding: 8px;
  border: 1px solid #999999;
}

/* Mark links that open in a new tab */
a[target="_blank"]::after {
  content: " ↗";
}

/* Images without alt text: highlight them during development */
img:not([alt]) {
  outline: 4px solid red;
}

/* Style using data-* attributes set by JavaScript */
.tab[data-state="active"] {
  border-bottom: 3px solid navy;
}

The last pattern is very common in modern front-end code: JavaScript changes data-state, and CSS reacts to it. (:not() is explained in the next chapter.)


Common Mistakes

  • Confusing A B and A > B: the space reaches any depth; > reaches only one level.

  • Expecting + or ~ to select earlier siblings or elements with a different parent — they only look forward among the same parent's children.

  • Expecting the left element to be styled: in h2 + p the p is styled, never the h2.

  • Using [class="btn"] to find buttons — it fails as soon as a second class is added. Use .btn.

  • Using *= too loosely: [href*="pdf"] also matches /pdf-guide.html. Use $=".pdf" for file extensions.

  • Overly long chains like body div.main ul li a — fragile and hard to override.


Interview / Exam Questions

1. What is the difference between div p and div > p?

div p selects every p that is a descendant of a div at any depth. div > p selects only p elements whose parent is a div.

2. Given <h2></h2><p>A</p><p>B</p><div></div><p>C</p>, which paragraphs do h2 + p and h2 ~ p select?

h2 + p selects only A (immediately after the h2). h2 ~ p selects A, B and C — all following sibling paragraphs, even though a div sits between B and C.

3. Can CSS combinators select a parent element?

No. Combinators only move to descendants or following siblings. Selecting a parent (or previous sibling) based on what follows requires the :has() pseudo-class, e.g. li:has(> a.active).

4. Which elements does [lang|="en"] match: lang="en", lang="en-US", lang="eng", lang="EN"?

en and en-US match. eng does not (no hyphen after en). EN also matches in HTML documents, because browsers treat the value of the lang attribute case-insensitively.

5. Write a selector for links whose URL ends in .zip or .rar.
a[href$=".zip"],
a[href$=".rar"] {
  font-weight: bold;
}
6. In which direction do browsers match the selector .menu li a, and why?

Right to left. The browser first checks whether an element is an a (the key selector), which quickly rules out most elements, and only then walks up the ancestors looking for an li and then a .menu. Starting from the right avoids testing every possible descendant of every .menu.


Summary

  • Descendant A B: B anywhere inside A.

  • Child A > B: B directly inside A.

  • Next sibling A + B: B immediately after A.

  • Subsequent sibling A ~ B: B anywhere after A, same parent.

  • The rightmost element is the one styled; browsers match right to left.

  • Attribute selectors: [a], [a="v"], [a~="v"], [a|="v"], [a^="v"], [a$="v"], [a*="v"]; add i for case-insensitive matching.

  • Attribute selectors have the same specificity as class selectors.

Next, in Pseudo-classes & Pseudo-elements, we'll select elements by their state (hovered, focused, checked) and position (first, last, every second), and style parts of elements that don't even exist in the HTML.