Beginner20 min read

CSS Selectors

Master the different ways to target HTML elements with CSS selectors, including element, class, ID, grouping, and descendant selectors.

Targeting Elements with Selectors

A CSS selector determines which HTML elements a set of styles will apply to. Choosing the right selector is one of the most important skills in CSS. Here are the most common types:

  • Element selector — Targets all elements of a given type. Writing p { ... } styles every <p> on the page.

  • Class selector — Targets elements with a specific class attribute. Prefixed with a dot: .highlight { ... } targets <span class="highlight">.

  • ID selector — Targets a single element with a specific id attribute. Prefixed with a hash: #header { ... } targets <div id="header">. IDs should be unique per page.

  • Universal selector — The asterisk * targets every element on the page. Useful for resets, but use sparingly.

Class selectors are the workhorse of CSS. Unlike IDs, a class can be applied to multiple elements, and an element can have multiple classes.

Class and ID Selectors in Action

html
<style>
  /* Element selector — all paragraphs */
  p {
    font-size: 16px;
  }

  /* Class selector — elements with class="highlight" */
  .highlight {
    background-color: yellow;
    padding: 4px;
  }

  /* ID selector — the one element with id="title" */
  #title {
    color: darkblue;
    font-size: 28px;
  }
</style>

<h1 id="title">CSS Selectors</h1>
<p>This is a normal paragraph.</p>
<p class="highlight">This paragraph is highlighted.</p>

Combining Selectors

You can combine selectors to create more specific targeting rules:

  • Grouping selector — Apply the same styles to multiple selectors by separating them with commas.

    css
    h1, h2, h3 { color: navy; }
  • Descendant selector — Target elements nested inside another element by separating selectors with a space.

    css
    article p { color: gray; }

    This styles only <p> elements that are inside an <article>, leaving other paragraphs unaffected.

  • Chaining selectors — Combine a tag and class (no space) to target elements that match both.

    css
    p.intro { font-size: 20px; }

    This targets only <p class="intro">, not other .intro elements or other <p> elements.

Descendant selectors are extremely useful for scoping styles to specific sections of a page without adding extra classes everywhere.

Which selector targets an element with class="card"?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.