CSS from Zero: How Ugly Pages Get Pretty
How CSS attaches paint, spacing, and layout to plain HTML, why your rules sometimes lose arguments with each other, and how to center anything without crying.
You'll learn how CSS finds HTML elements and styles them, how the box model controls spacing, why CSS rules sometimes ignore you (specificity), and how Flexbox aligns layouts in a few lines. All you need is a browser and a text editor.
1. HTML is the skeleton; CSS is the wardrobe
If you open a plain HTML file in a browser, it looks like a 1994 government memo: black Times New Roman text on a white background, jammed against the left edge of the screen. That is not a bug. HTML's job is to say what things are ("this is a heading", "this is a button"). It has no opinion on how things should look.
CSS (Cascading Style Sheets) is a separate language whose only job is appearance: colors, fonts, spacing, borders, and where things sit on the screen.
You write a CSS rule in two parts:
- A selector (who are we talking to?)
- A declaration block inside
{ ... }(what are we changing?)
h1 {
color: #ff2e88;
font-size: 40px;
}Read that aloud: "Find every <h1> on the page. Make its text color hot pink (#ff2e88), and make its font size 40 pixels."
Every line inside { ... } is a property (color), a colon :, a value (#ff2e88), and a semicolon ; at the end. Forget the semicolon and CSS quietly breaks that rule and sometimes the one after it, without saying a word.
2. How CSS attaches to your HTML
You can write CSS in a separate file called styles.css and link it inside your HTML's <head>:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Gerald's Styled Page</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>Gerald's Status Page</h1>
<p>Still tired, now in a nicer font.</p>
</body>
</html>The <link> tag tells the browser: "Before you draw this page, go read styles.css in the same folder."
Here is a starter styles.css that immediately rescues the page from 1994:
body {
background-color: #07060d;
color: #e9e7f5;
font-family: system-ui, sans-serif;
line-height: 1.6;
padding: 40px;
}
h1 {
color: #19f0ff;
}Save both files in the same folder and refresh your browser. Suddenly you have a dark background, crisp system font, comfortable line spacing, and a cyan heading.
If nothing changed, check two things first:
- Are
index.htmlandstyles.cssin the exact same folder? - Did you spell
href="styles.css"andrel="stylesheet"correctly? Missrel="stylesheet"and the browser downloads the file and stares at it blankly.
Change background-color to #12101f and color on h1 to #ff2e88. Save styles.css and refresh your browser to confirm your stylesheet is connected.
3. Selectors: targeting one thing instead of everything
Targeting p styles every <p> on the whole page. Usually you want more precision: "make the warning paragraph red, not every paragraph in the building."
That is what classes are for. In HTML, you attach a class attribute to any element. In CSS, you target a class with a leading dot .:
<p>Normal update: the server is running.</p>
<p class="warning">Warning: Gerald touched production.</p>p {
color: #e9e7f5;
}
.warning {
color: #ff2e88;
font-weight: bold;
}You can put the same class on ten different elements, or put multiple classes on one element separated by spaces (class="card warning").
There is also #id (using id="hero" in HTML and #hero in CSS), which is meant for one unique element on a page. Most CSS authors stick to .class selectors for styling and save id for links (#section-2) and JavaScript hooks—you'll see why in a moment.
4. The Box Model: why nothing fits where you expect
In CSS, every single HTML element is a rectangle. Even a round button or a single word in a paragraph lives inside an invisible rectangle.
Every rectangle has four layers, from the inside out:
- Content — the actual text or image.
- Padding — breathing room inside the box, between the text and the border. Padding shares the element's background color.
- Border — the outline wrapped around the padding.
- Margin — empty space outside the border, pushing neighboring elements away.
Think of a framed painting: the canvas is content, the white mat around it is padding, the wooden frame is border, and the empty wall between this frame and the next painting is margin.
.card {
width: 300px;
padding: 20px;
border: 2px solid #19f0ff;
margin: 24px;
background-color: #12101f;
}Now here is the trap that has ruined more afternoons than daylight saving time:
By default, CSS measures width: 300px on the content alone, and then adds padding and border on top. So .card above is actually 300 + 20 + 20 + 2 + 2 = 344px wide! If you put two 50% columns side by side and add 10px of padding, their total width becomes 100% + 40px, and the second column falls onto the next line.
Fix this once at the very top of every CSS file you ever write:
*,
*::before,
*::after {
box-sizing: border-box;
}box-sizing: border-box tells CSS: "When I say width: 300px, I mean the entire box—content, padding, and border combined—is 300px." Sane, predictable, zero surprise math.
Right-click your .card in the browser, choose Inspect, and look at the box diagram in DevTools. Hover over padding, border, and margin to see each layer highlight on the page.
5. The Cascade and Specificity: why CSS ignores you
Ever written a CSS rule, refreshed the page, and watched nothing happen? Usually it is not broken—your rule just lost an argument with another rule.
CSS stands for Cascading Style Sheets. When two rules target the same element and set the same property (say, color), CSS has two tie-breakers:
- Specificity (how specific the selector is):
- An
#idselector beats a.classselector. - A
.classselector beats a plain tag selector (p,h1).
- An
- Order (who came last):
- If two selectors are equally specific, whichever appears lower in the file wins.
.warning {
color: #ff2e88;
}
p {
color: #19f0ff;
}Even though p comes after .warning, <p class="warning"> stays pink (#ff2e88), because .warning (a class) is more specific than p (a tag).
If you ever find yourself writing !important to force a rule to win, stop—!important is the CSS equivalent of screaming louder in a meeting. Instead, check DevTools to see which more-specific selector is beating yours, and simplify your selectors.
Style almost everything with single .class selectors. When every rule has the same specificity, the order in your file decides the winner cleanly.
6. Flexbox: aligning things without losing your mind
By default, block elements like <p>, <div>, and <h1> stack vertically like bricks. If you want a horizontal navigation bar, a row of cards, or a button centered inside a box, use Flexbox.
You turn Flexbox on by putting display: flex on the parent container—not the children:
<nav class="navbar">
<span class="brand">CodeHeart</span>
<div class="links">
<a href="/go">Go</a>
<a href="/python">Python</a>
<a href="/web">Web</a>
</div>
</nav>.navbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 24px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.links {
display: flex;
gap: 20px;
}Four properties handle 90% of Flexbox layouts:
display: flex— puts the direct children in a row.align-items: center— lines them up vertically in the middle.justify-content: space-between— pushes the brand to the left and the links to the right.gap: 20px— puts clean20pxspacing between the links without messy margins on the first or last link.
Want to center something dead-center horizontally and vertically inside a container?
.hero-box {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 300px;
gap: 12px;
}Remove flex-direction: column from .hero-box and refresh. Notice how the children immediately snap into a horizontal row, and put flex-direction: column back.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Forgot the . on a class (warning { ... }) | Browser looks for an HTML <warning> tag and styles nothing | Prefix classes with a dot: .warning { ... } |
Missing ; at end of a line | That property (and often the next one) is silently ignored | End every property: value; line with ; |
Put display: flex on the child | Nothing lines up | Put display: flex on the parent wrapping the items |
Two 50% boxes wrap onto two lines | Padding/border pushed total width past 100% | Add box-sizing: border-box globally |
Wrote p { color: red } to override .note | .note still wins because class beats tag | Target .note directly or use a more specific class |
Practice
Predict what happens before testing each one. Answers follow.
Exercise 1. Given <p id="intro" class="lead">Hello</p>, what color is the text?
#intro { color: cyan; }
.lead { color: pink; }
p { color: white; }Exercise 2. With box-sizing: border-box, you have .box { width: 200px; padding: 25px; border: 5px solid white; }. How wide is .box on screen, and how wide is the inner space left for text?
Exercise 3. Why doesn't gap: 16px do anything here?
.list a {
gap: 16px;
}Answers
Exercise 1 is cyan—#intro (an ID) has higher specificity than .lead (a class) and p (a tag), regardless of order.
Exercise 2 is 200px wide on screen. Padding (25px left + 25px right = 50px) and border (5px + 5px = 10px) are subtracted from the inside, leaving 140px for the text.
Exercise 3 does nothing because gap only works on a Flex or Grid container, and .list a targets the child links. Put display: flex; gap: 16px; on .list instead.
Capstone
Combine index.html and styles.css into a clean dark-mode status card centered on the page:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Status Card</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body class="page">
<main class="card">
<span class="badge">Operational (barely)</span>
<h1>Gerald's API</h1>
<p>Uptime: 99.9%. Remaining coffee: 0%.</p>
<a class="btn" href="https://codeheart.tech">Read the docs</a>
</main>
</body>
</html>*,
*::before,
*::after {
box-sizing: border-box;
}
.page {
margin: 0;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: #07060d;
color: #e9e7f5;
font-family: system-ui, sans-serif;
}
.card {
width: 100%;
max-width: 380px;
padding: 28px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 16px;
background: #12101f;
}
.badge {
display: inline-block;
padding: 4px 10px;
border-radius: 999px;
background: rgba(25, 240, 255, 0.12);
color: #19f0ff;
font-size: 13px;
font-weight: 600;
}
.btn {
display: inline-block;
margin-top: 16px;
padding: 10px 18px;
border-radius: 10px;
background: #ff2e88;
color: #07060d;
font-weight: 600;
text-decoration: none;
}What you learned
- CSS pairs selectors (
.card,h1) with declarations (property: value;) to style HTML. - Every element is a rectangle with four layers: content, padding, border, margin.
box-sizing: border-boxstops padding and borders from inflating your widths.- When rules conflict, specificity (
#id>.class>tag) wins first, then file order. - Flexbox (
display: flexon the parent) handles alignment and spacing withalign-items,justify-content, andgap.
Next up: making the page actually respond when someone clicks a button—with JavaScript.