CSS Selectors & Combinators

Difficulty: Beginner

Question

What are the different types of CSS selectors? Explain combinators.

Answer

CSS selectors target elements for styling:

1. Simple: element (div), class (.nav), ID (#header), universal (*) 2. Attribute: [type='text'], [href^='https'], [class~='active'] 3. Combinators: - Descendant (space): div p (any p inside div) - Child (>): div > p (direct child p only) - Adjacent sibling (+): h2 + p (p immediately after h2) - General sibling (~): h2 ~ p (all p siblings after h2) 4. Pseudo-classes: :hover, :first-child, :nth-child() 5. Pseudo-elements: ::before, ::after, ::placeholder

Code examples

Selector Types

/* Element selector */
p { color: #333; }

/* Class selector */
.highlight { background: yellow; }

/* ID selector */
#hero { height: 100vh; }

/* Universal selector */
* { margin: 0; padding: 0; }

/* Attribute selectors */
[type="email"] { border-color: blue; }
[href^="https"] { color: green; }  /* starts with */
[href$=".pdf"] { color: red; }     /* ends with */
[class*="btn"] { cursor: pointer; } /* contains */

/* Grouping */
h1, h2, h3 { font-family: serif; }

/* Chaining (must match all) */
input.large[required] {
  border: 2px solid red;
}

Attribute selectors are powerful for targeting elements without adding classes. ^= starts with, $= ends with, *= contains.

Combinators

/* Descendant: any level deep */
.card p { margin-bottom: 0.5rem; }
/* Matches <div class='card'><div><p>this</p></div></div> */

/* Child: direct children only */
.card > p { font-weight: bold; }
/* Only matches <div class='card'><p>this</p></div> */

/* Adjacent sibling: immediately after */
h2 + p { font-size: 1.2rem; }
/* Only the first <p> right after <h2> */

/* General sibling: all after */
h2 ~ p { color: #666; }
/* All <p> elements after <h2> at same level */

/* Combining combinators */
.sidebar > ul > li > a:hover {
  color: blue;
}

Child (>) is stricter than descendant (space). Adjacent (+) targets one element, general sibling (~) targets all matching siblings.

Practical Selector Patterns

/* Style links by type */
a[href^="http"]:not([href*="mysite.com"]) {
  /* External links */
  color: #e74c3c;
}
a[href^="mailto:"] {
  /* Email links */
  color: #3498db;
}

/* Style empty elements */
.card:empty {
  display: none;
}

/* First and last items */
.nav-item:first-child { margin-left: 0; }
.nav-item:last-child { margin-right: 0; }

/* Every other row */
tbody tr:nth-child(odd) {
  background: #f8f9fa;
}

/* All except first */
.list-item:not(:first-child) {
  border-top: 1px solid #eee;
}

Combining selectors with :not() and attribute selectors can replace many JavaScript-based style toggles.

Key points

Concepts covered

CSS Selectors, Combinators, Attribute Selectors, Pseudo-classes, Specificity