Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Published
2 min read

Why do we need CSS selectors?

CSS is how we style our webpages, but first, we need a way to choose which elements to style.

  • CSS selectors are like addresses for elements

  • They tell the browser: “Hey, style this element like this!”

Think of it like sending invitations:

  • Element = person

  • Selector = their address

  • CSS rules = the gift you’re sending


Element selector

The element selector targets all elements of a certain type.

Example:

p {
  color: blue;
}
  • Targets all <p> tags on the page

  • Makes all paragraphs blue


Class selector

The class selector targets elements with a specific class.

Example:

.highlight {
  background-color: yellow;
}

HTML:

<p class="highlight">Important text</p>
<p>Normal text</p>
  • Only the paragraph with class highlight gets yellow background

  • Prefix with . in CSS


ID selector

The ID selector targets a unique element with a specific ID.

Example:

#main-title {
  font-size: 2rem;
  color: red;
}

HTML:

<h1 id="main-title">Welcome</h1>
  • Only the element with id="main-title" is styled

  • Prefix with # in CSS

  • IDs should be unique on a page


Group selectors

Group selectors let us apply the same style to multiple selectors.

Example:

h1, h2, h3 {
  font-family: Arial, sans-serif;
}
  • All headings (<h1>, <h2>, <h3>) get the same font

  • Saves repeating rules


Descendant selectors

Target elements inside other elements.

Example:

div p {
  color: green;
}

HTML:

<div>
  <p>This is green</p>
</div>
<p>This is not green</p>
  • Only paragraphs inside <div> are green

  • Think of it as addressing someone inside a house


Basic selector priority (very high level)

When multiple selectors could apply, CSS follows a priority order:

  1. ID selectors → highest priority

  2. Class selectors → medium priority

  3. Element selectors → lowest priority

Example:

p { color: blue; }
.highlight { color: yellow; }
#special { color: red; }

HTML:

<p id="special" class="highlight">Text</p>
  • Text will be red → ID beats class and element

Quick tips for learners

  • Inspect elements in browser dev tools → see which CSS applies

  • Start with element → class → ID

  • Experiment with group and descendant selectors

  • Selectors are the foundation of CSS — all styling depends on them


Key takeaway:

  • CSS selectors = how we choose elements to style

  • Element → Class → ID = basic order

  • Group and descendant selectors = more precise targeting

  • Understanding selectors first makes all CSS easier 🚀