DevLab
CSS

CSS Selectors: The Complete Guide

Learn every type of CSS selector — from basic to advanced — with examples and specificity explanations.

Basic Selectors

CSS selectors determine which HTML elements a rule applies to. They range from simple to highly specific.

  • * — Universal selector: matches everything
  • p — Type selector: matches all <p> elements
  • .class — Class selector: matches elements with that class
  • #id — ID selector: matches the element with that ID
  • [attr] — Attribute selector: matches elements with that attribute

Combinators

Combinators describe the relationship between selectors:

  • div p — Descendant: any <p> inside a <div>
  • div > p — Child: direct child <p> of <div>
  • h1 + p — Adjacent sibling: <p> immediately after <h1>
  • h1 ~ p — General sibling: any <p> after <h1>

Pseudo-classes

Pseudo-classes select elements based on state or position:

  • :hover, :focus, :active — Interaction states
  • :first-child, :last-child, :nth-child(n) — Position
  • :not(.class) — Negation
  • :is(h1, h2, h3) — Forgiving selector list
  • :where(header, footer) — Like :is() but zero specificity

Pseudo-elements

Pseudo-elements create virtual elements you can style:

  • ::before, ::after — Insert content
  • ::first-line, ::first-letter — Text formatting
  • ::placeholder — Style input placeholder text
  • ::selection — Style selected text

Attribute Selectors

Attribute selectors offer powerful matching for HTML attributes:

  • [href] — Has href attribute
  • [href="url"] — Exact value
  • [href^="https"] — Starts with
  • [href$=".pdf"] — Ends with
  • [class*="btn"] — Contains

Practice with these tools

More Learning Topics