CSS Selector: Simple, Compound, Combinator, Complex

By Xah Lee. Date: .

ai answer

CSS Selectors are patterns used to select HTML elements to style them. They are the core of CSS.

CSS selectors are broadly classified into several categories:

1. Simple Selectors

These target elements based on a single criterion.

2. Compound Selectors

A compound selector is a sequence of simple selectors without any combinators between them. It represents an element that matches all the conditions simultaneously.

Examples:

Compound selectors are powerful because they increase specificity without adding extra rules.

3. Combinators (Relationship Selectors)

Combinators define the relationship between two or more selectors. They are placed between selectors.

Combinator Name Description Example Meaning
(space) Descendant combinator Selects elements that are anywhere inside another element div p Any <p> inside a <div> (even nested)
> Child combinator Selects direct children only ul > li <li> that are direct children of <ul>
+ Adjacent sibling Selects the element that is immediately next sibling h2 + p <p> that comes right after an <h2>
~ General sibling Selects all following siblings (not necessarily immediate) h2 ~ p All <p> that come after an <h2> at the same level

Important notes on combinators:

4. Other Important Selector Types

Complex Selectors

A selector that contains at least one combinator is called a complex selector.

Selector Lists

Multiple selectors separated by commas (logical OR):

h1, h2, h3, .title {
  font-family: sans-serif;
}

Pseudo-class Functions (newer powerful ones)

Specificity Rules (Quick Reminder)

Specificity determines which rule wins when multiple selectors match the same element.

Order (highest to lowest):

  1. Inline styles (style="...")
  2. ID selectors
  3. Classes, attributes, pseudo-classes
  4. Elements, pseudo-elements

Compound selectors add up specificity. Combinators themselves do not add specificity (except the :is()/where() behavior).

Examples in Action

/* Simple + Compound */
p.special { color: blue; }
#hero { font-size: 2rem; }

/* Combinators */
article > h2 { margin-top: 0; }           /* direct child */
nav ul li + li { border-left: 1px solid; } /* adjacent siblings */
h1 ~ p { margin-top: 0.5em; }             /* general siblings */

/* Complex compound */
div.content > p:first-child { font-weight: bold; }

/* Modern */
:is(h1, h2, h3) { line-height: 1.2; }
article:has(> img) { border: 1px solid; }

Summary Table

Category Purpose Contains Combinators? Example
Simple Basic matching No .class, div
Compound Multiple conditions on one element No a.button:hover
Complex Relationships between elements Yes div p
Selector List Group rules Can h1, h2, .title

CSS, Selectors