Skip to main content

CSS Selectors 101: Targeting Elements with Precision

Published 2 min readMarkdown

1. Why we need Selectors

If we just wrote "color: red," the browser wouldn't know which text to change. We need selectors to "address" the elements. It is just like sending a letter—we need a specific address so it doesn't go to the wrong house.

2. The Big Three Selectors

We mostly use these three to get things done:

* Element Selector: We just type the tag name (like h1 or p). This picks every single one of those on the page.

* Class Selector (.class-name): We use a dot before the name. This is like a group. We can give five different buttons the same class and style them all at once.

* ID Selector (#id-name): We use a hashtag. This is for someone "special." An ID should only be used for one element on the whole page.

3. Grouping and Descendants

Sometimes we want to be fancy to save time:

* Group Selectors: If we want h1, h2, and p to all be green, we just separate them with commas: h1, h2, p { color: green; }.

* Descendant Selectors: This is for when we want to target something inside something else. Like "only the <span> inside a <div>." We just put a space between them: div span { ... }.

4. Priority

If we tell a paragraph to be red using its tag, but blue using its ID, what happens? CSS has a "priority" system.

Basically, ID wins over Class, and Class wins over the Element tag. The more specific we are, the more the browser listens to us!

5. Seeing is Believing

I found that the best way to learn is to change the color of everything to something ugly like "hotpink" just to see if our selector works. Once we can point at the right thing, the rest of CSS is just picking pretty colors…

No comments yet. Be the first to comment.