CSS Basics: Selectors, Which Rule Wins, and the Box Model
HTML says what each piece is, CSS says how it looks. Learn the parts of a rule, five selectors, why an id rule beats a class rule, and how padding, border and margin add up to 348px unless you use border-box.
What you will learn
- Read a CSS rule: selector, property, value, declaration
- Pick elements with tag, class, id, descendant and :hover selectors
- Predict which rule wins: id beats class, class beats tag, later wins a tie
- Work out an element's width with padding, border, margin and box-sizing
Before you start
- HTML tags, elements and attributes
Take a plain HTML page and add one file, style.css. The heading turns blue, the links turn green, the notes get a yellow background, and not one HTML tag changed. HTML says what each piece is. CSS says how it looks.
Three places to write CSS
- Inline, a
styleattribute on one tag. It styles only that tag. - A
<style>tag in the head. It styles only this page. - A linked file,
<link rel="stylesheet" href="style.css">. Every page that links it gets the same look. This is the one you'll use most.
The parts of a CSS rule
Values come in a few kinds you'll see all the time. A colour like #1E40AF is three pairs of hex digits for red, green and blue; simple names like red or white work too. A size in px is screen pixels, and rem means "times the normal text size": normal text is 16px, so 2rem is 32px. A font like Arial, sans-serif means "use Arial, and if it isn't installed, any plain sans-serif font".
Five selectors on one page
Here's the HTML:
<h1>Web Basics</h1>
<nav>
<a href="#tasks">Tasks</a>
<a href="#students">Students</a>
</nav>
<p class="note">Week 1: three small tasks.</p>
<p>Ask <a href="#emma">Emma Clarke</a> if you get stuck.</p>
<p class="note" id="deadline">Deadline: Friday.</p>
And the stylesheet:
/* tag: every <body> and every <h1> */
body { font-family: Arial, sans-serif; }
h1 { color: #1E40AF; font-size: 2rem; }
/* class: every tag with class="note" */
.note { background: #FEF3C7; padding: 8px; }
/* id: the one tag with id="deadline" */
#deadline { border-left: 6px solid #B91C1C; }
/* descendant: only an <a> inside <nav> */
nav a { color: #047857; margin-right: 16px; }
/* :hover - only while the mouse is on it */
nav a:hover { color: #B91C1C; }
h1is a tag selector. It picks everyh1; here there's one, so the heading turns blue..noteis a class selector. The dot means class. Both paragraphs withclass="note", the week 1 note and the deadline, turn yellow.#deadlineis an id selector. The hash means id, and it picks exactly one tag, which gets a red line on the left.nav ais a descendant selector. The space means "inside", so only Tasks and Students turn green. The "Emma Clarke" link is also ana, but it's not insidenav, so it keeps the browser's normal blue.nav a:hoveradds a state. The colon rule applies only while the mouse is on the link, so the link under the mouse turns red and goes back to green when you move away. No JavaScript needed.
Which rule wins?
Two rules can give one tag two different colours. Picture a classroom. The teacher says "everyone, grey": that's a tag rule, and every student turns grey. Then "group B, green": that's a class, more exact, so group B turns green. Then "Emma Clarke, red": that's an id, called by name, the most exact of all. Emma heard all three, but she follows her own name.
So an id beats a class, and a class beats a tag. If two rules are equally exact, the one written later wins. This ranking is called specificity.
<h1 id="welcome" class="title">Web Basics</h1>
<p class="title">Week 1 starts on Monday.</p>
/* two rules aim at the same heading */
h1 {
color: #6B7280; /* tag rule: grey */
}
.title {
color: #047857; /* class rule: green - a class beats a tag */
}
/* BREAK IT: remove the comment marks around the id rule below.
An id beats a class, so the heading turns red and the .title
colour is crossed out in DevTools (Styles tab). */
/* #welcome { color: #B91C1C; } */
As written, h1 says grey and .title says green, and the class wins: the heading is green. Now remove the comment marks around #welcome. The heading turns red, with no error anywhere. Press F12 and the Styles tab in DevTools shows why: the .title colour is crossed out. It's still there; it just lost. The paragraph has no id, so it stays green.
When a style "doesn't work", this is the first place to look. The rule is usually fine and a more exact rule is beating it.
Every element is a framed picture
The other big idea in CSS is space. Every element is like a framed picture on a wall. The picture in the middle is the content. The mat around it is the padding. Then comes the frame, the border. And the wall up to the next picture is the margin. Padding is inside the frame; margin is outside.
/* width now includes padding and border */
* { box-sizing: border-box; }
body { font-family: Arial, sans-serif; }
.card {
width: 300px;
padding: 20px; /* space inside the frame */
border: 4px solid #1E40AF; /* the frame itself */
margin: 24px; /* space outside, on the wall */
background: #EFF6FF;
}
The HTML is two task cards, each a div with class="card". In DevTools the layers show in colour: the content is 252 by 102 pixels, the padding is 20px on every side, the border is 4px and the margin is 24px, the wall between the two cards. The light blue background fills the padding too, but the margin stays empty, because it's the wall, not the picture.
The width you write, or more?
width: 300px card with and without box-sizing: border-box.By default, width means only the picture. Padding and border are added on top: 20 + 4 + 300 + 4 + 20 = 348 pixels, so the frame runs past the 300 line. With box-sizing: border-box, the padding and border fit inside. The card is 300 pixels frame to frame, and the content shrinks to 252.
That's why line 2 of the file is * { box-sizing: border-box; }. Put it at the top of every stylesheet and the width you write is the width you get.
Common mistakes
- A class rule that "does nothing". An id rule or a later rule is beating it. Check the crossed-out lines in the DevTools Styles tab.
- Forgetting the dot or hash.
note { }looks for a<note>tag, which doesn't exist. - Mixing up padding and margin. Background colour fills the padding, never the margin.
- Boxes wider than you set. Add
box-sizing: border-box.
Quick recap
| Selector | Picks | Strength |
|---|---|---|
h1 | every tag of that kind | weakest |
.note | every tag with that class | beats a tag |
#deadline | the one tag with that id | beats a class |
nav a | an a inside a nav | adds up its parts |
nav a:hover | the same, only while hovered | a state |
Try it yourself
In the box model example, give the first card a class and an id, colour it with both, and predict which one wins before you reload. Then open DevTools, change the padding, border and margin live, and watch the coloured layers move. Next up: putting boxes side by side with Flexbox and Grid.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
Semantic HTML: header, nav, main, aside and footer as Page Landmarks
The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.
