Stop 04 · CSS FundamentalsTopics · 2/9

CSS Selectors

Part of the Web Development Roadmap

In short

Before CSS can paint anything, it has to find the right element. Selectors are how you point at things, and most 'why isn't my style working' bugs start here.

Selectors choose which elements a rule styles, from simple tag, class and id selectors to descendant, child and attribute selectors.

The jaadu mascot as a hostel warden calls through a megaphone down a corridor of room doors.

Think of it like this

The hostel warden's announcements

'Everyone, come down' is the universal selector. 'Second floor, lights off' is a class. 'Room 204, see me' is an ID. 'Second-floor boys in the common room' is a combined selector. The more specific the call, the fewer people it reaches.

Watch it happen

Which elements does each selector hit?

body
nav
a
a
main
h2
p
div.card

1/4nav > a picks only links that are direct children of nav.

The big ideas

What you need to know

Type, class, ID

p picks all paragraphs, .card picks a class, #logo picks one ID. Classes are what you'll use most.

Combinators

A space means 'inside', > means 'direct child', + means 'right after'. So nav > a picks links directly in nav.

Specificity decides ties

When two rules clash, the more specific one wins: ID beats class, class beats tag. If equal, the later rule wins.

Attribute and :is()

input[type="email"] picks by attribute. :is(h1, h2, h3) groups selectors in one go.

See it in code

Walk through the code

css
1/* Every card */2.card { padding: 1rem; }3 4/* Links directly inside the nav only */5nav > a { text-decoration: none; }6 7/* A paragraph right after any heading */8:is(h2, h3) + p { margin-top: 0; }9 10/* Only email inputs */11input[type="email"] { border-color: teal; }12 13/* A card that also has the "featured" class */14.card.featured { border: 2px solid gold; }

1/4A class selector. The one you'll use most.

Notice .card.featured has no space (both classes on one element) while nav > a has a combinator (one element inside another).

Save yourself the pain

Common mistakes

Oops

Styling with IDs everywhere, like #header #menu li a.

Do this instead

Use simple class selectors. Long, ID-heavy selectors are hard to override later.

Oops

Throwing !important at a style that won't apply.

Do this instead

Open DevTools, see which rule is winning and why, then fix the selector.

Your mission

Selector sniper

~20 min

Quick check

Both rules target the same button. Which colour does it get? .btn { color: red; } then button.btn { color: blue; }

Go deeper

  1. 1Style a page using mostly class selectors and keep ids for JavaScript hooks.
  2. 2Practise selectors on a CSS selector game website.
  3. 3Use the descendant and child selectors to style links only inside the nav.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge