Combining CSS Selectors — Compound and Complex Selector Patterns

Learn how to combine CSS selectors to create precise targeting rules. Covers compound selectors (chaining), complex selectors (combinators), and selector lists (comma-separated).

Advanced Patterns

Detailed Explanation

Combining CSS Selectors

CSS becomes powerful when you combine simple selectors into compound and complex patterns. Understanding how to combine them effectively is key to writing maintainable stylesheets.

Compound Selectors (Chaining)

Chain selectors without spaces to match elements with multiple attributes:

/* Element with tag AND class */
div.container { }

/* Element with two classes */
.btn.primary { }

/* Element with class AND attribute */
input.large[required] { }

/* Element with class AND pseudo-class */
.item:first-child { }

Complex Selectors (Combinators)

Use combinators to express relationships between elements:

/* Descendant */
.sidebar .widget { }

/* Child */
.nav > li { }

/* Adjacent sibling */
h2 + p { }

/* General sibling */
.toggle:checked ~ .content { }

Selector Lists (Comma-Separated)

Group selectors that share the same styles:

h1, h2, h3 {
  font-family: serif;
  line-height: 1.2;
}

.btn-primary,
.btn-secondary,
.btn-outline {
  padding: 0.5rem 1rem;
  border-radius: 4px;
}

Specificity of Combined Selectors

Specificity is additive:

  • div.container = (0, 1, 1)
  • .nav > li.active = (0, 2, 1)
  • #main .sidebar .widget h3 = (1, 2, 1)
  • a:hover = (0, 1, 1)

Best Practices

  1. Keep selectors as short as possible (max 3-4 parts)
  2. Avoid qualifying classes with elements (.nav not ul.nav)
  3. Use selector lists to reduce duplication
  4. Prefer classes over complex descendant chains

Use Case

Combining selectors is a fundamental skill for every CSS developer. It enables precise targeting for component variants (.btn.primary vs .btn.secondary), state-based styling (.input.error:focus), layout patterns (.grid > .col:nth-child(3n)), and responsive design patterns. Understanding selector combination is essential for debugging specificity conflicts and writing efficient stylesheets.

Try It — CSS Selector Tester

Open full tool