DevAcademy
LearnCSSCSS Selectors
BeginnerCSS

CSS Selectors

Learn how to target elements using type, class, ID, universal, and attribute selectors.

Reading Time

16 min

Lesson

Lesson 4 of 30

What Selectors Do

A selector determines which HTML elements a rule applies to. CSS offers many kinds of selectors, from simple element names to precise attribute matching.

Basic Selector Types

SelectorExampleTargets
TypepEvery <p> element
Class.highlightEvery element with class="highlight"
ID#headerThe single element with id="header"
Universal*Every element on the page
Attribute[type="email"]Every element with a matching attribute

Type, Class, and ID Selectors

<style>
  p {
    color: #333;
  }
  .highlight {
    background: yellow;
  }
  #main-title {
    font-size: 28px;
  }
</style>

<h1 id="main-title">Main Title</h1>
<p>Regular paragraph.</p>
<p class="highlight">Highlighted paragraph.</p>
Output

Attribute Selectors

Attribute selectors target elements based on the presence or value of an HTML attribute, useful for styling form inputs by type without adding extra classes.

Attribute Selectors Example

<style>
  input[type="email"] {
    border-color: steelblue;
  }
  a[target="_blank"] {
    color: darkorange;
  }
</style>

<input type="email" placeholder="you@example.com" />
<a href="https://example.com" target="_blank">External Link</a>
Output

Grouping Selectors

Multiple selectors can share the same declaration block by separating them with commas, avoiding repeated rules.

Grouped Selectors

<style>
  h1, h2, h3 {
    font-family: Georgia, serif;
    color: #222;
  }
</style>

<h1>Heading 1</h1>
<h2>Heading 2</h2>
Output

Class vs ID Selectors

Prefer class selectors for styling — they can be reused across many elements. Reserve ID selectors for unique, one-off cases, since an id must be unique per page and carries higher specificity that can be harder to override later.

Best Practice

Default to class selectors for anything reusable. Keep selectors as simple and flat as possible — deeply nested selectors become fragile and hard to override.

Interview Questions

Quick Quiz

1. Which selector targets every element with class="card"?

2. Which selector targets the single element with a given id?

3. How do you apply the same styles to h1, h2, and h3 without repeating the rule?