22 min read
How CSS Works
Rules, selectors, properties and values; inline, internal and external CSS; linking a style sheet; comments and the cascade.
A CSS Rule
One ruleCSS
h1 { color: #5A3825; font-size: 36px;}| Parts of a rule | ||
|---|---|---|
Three Ways to Add CSS
Where CSS can go
| Method | When to use it |
|---|---|
Inline — a style attribute: <p style="color: red;"> | Almost never — it mixes style with content and must be repeated everywhere |
Internal — a <style> element in the head | Quick tests, or a single-page site |
External — a separate .css file linked with <link> | Always for real websites — one file styles every page |
Linking an External Style Sheet
Kasun creates css/style.css and adds one line to the head of every page:
The link elementHTML
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Menu | Ceylon Leaf Tea Room, Galle</title> <link rel="stylesheet" href="css/style.css"></head>rel="stylesheet" says what the file is; href is the relative path to it. The preview below links to the example site's real style sheet — the plain HTML instantly takes on the finished design:
index.html
What the browser shows
Try it: Delete the <link> line and watch every style disappear. Put it back.
The Cascade
Cascading means several rules can apply to the same element, and CSS decides which wins:
- A more specific selector beats a less specific one (an id beats a class, which beats an element name — next lesson).
- If they are equally specific, the rule that comes later wins.
- Some properties, such as color and font-family, are inherited — set them on body and every element inside uses them unless told otherwise.
Which colour wins?CSS
p { color: black;} p { color: brown;}Both rules have the same selector, so the later one wins: paragraphs are brown.
Practice
Where does the <link> to the style sheet go?
More lessons in CSS · Next: Selectors · Previous: Introduction

Comments and Layout of a Style Sheet
Organising style.css with commentsCSS
CSS comments go between
/*and*/. Divide your style sheet into sections — base, header, navigation, tables, forms, gallery, footer — so you can find rules quickly.