CSS BasicsCore· 40 min read

CSS Selectors

Selectors decide WHICH elements get styled. Master these five and you can target anything.

What you will learn

  • Use element, class, id and universal selectors
  • Group selectors to share styles
  • Choose the right selector for the job

The five you need most

SelectorTargetsExample
pAll elements of that tagp { }
.classAll elements with that class.card { }
#idThe one element with that id#header { }
*Every element (universal)* { }
a, b, cSeveral selectors at once (grouping)h1, h2, p { }
All five selector types together
<style>
  * { font-family: sans-serif; }      /* everything */
  h1 { color: #4338ca; }              /* all h1 */
  .highlight { background: #fde68a; } /* class hook */
  #special { color: crimson; }        /* one element */
  p, li { color: #5b6178; }           /* grouped */
</style>

<h1>Heading</h1>
<p>A normal paragraph.</p>
<p class="highlight">I have the highlight class.</p>
<p id="special">I am the special one.</p>
<ul><li>A list item</li></ul>
Live preview

Match each rule to what changed on screen:

  • * (universal) gave everything a sans-serif font — even the list item.
  • h1 (element) coloured the heading indigo, because it targets every <h1> tag.
  • .highlight (class) gave the second paragraph a yellow background — it only hit the element with class="highlight".
  • #special (id) turned the third paragraph crimson — an id targets the one element with that exact id.
  • p, li (grouping) coloured both paragraphs and the list item grey in a single rule — the comma means “apply to all of these”.

Note: The takeaway: a tag name styles all of that tag, a .dot styles a reusable class, a #hash styles one unique element, * styles everything, and commas let one rule cover several targets.

Tip: Remember the prefixes: . for class (reusable, the one you use most) and # for id (unique). The class is your everyday tool.

Note: You will meet more powerful selectors later — combinators (div p), attribute selectors ([type="text"]) and pseudo-classes (:hover). These five are the foundation.

Q. How do you select all elements with class="btn"?

Answer: A class selector uses a dot: .btn. A # selects an id; no prefix selects a tag name.

✍️ Practice

  1. Style all paragraphs one colour, then override one special paragraph using an id.
  2. Create a .card class and apply it to three different elements so they share a style.
  3. Use grouping to give h1, h2 and h3 the same colour in one rule.

🏠 Homework

  1. Take your HTML profile page and add classes to the elements you will want to style, then write selectors for each.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →