Open any website you like: a news portal, an online shop, your college's result page. The text, headings, images and links all come from HTML. But the colours, fonts, spacing, the layout of the columns, the way a button changes colour when you hover over it — none of that is HTML. That is the work of CSS.
In this chapter we will understand what CSS is, why it exists, how a CSS rule is written, and how the browser actually uses CSS to draw a page on your screen. By the end you will have written and understood your first styled web page.
What is CSS?
CSS (Cascading Style Sheets) is a style sheet language used to describe how a document written in a markup language such as HTML should be presented — on screen, on paper, or in other media.
In simple words: HTML says what something is, CSS says how it should look.
HTML tells the browser "this is a heading", "this is a paragraph", "this is a list". CSS then tells the browser "headings should be dark blue and centred", "paragraphs should use an 18px font", "the list should sit in a sidebar on the right".
A common way to remember the three core web technologies:
| Technology | Role | House analogy |
|---|---|---|
| HTML | Structure and meaning of content | Walls, rooms, doors |
| CSS | Presentation: colours, fonts, spacing, layout | Paint, tiles, furniture arrangement |
| JavaScript | Behaviour and interactivity | Electricity, switches, appliances |
What does the name mean?
Style — it describes the visual style of a document (colour, font, size, position).
Sheets — styles are usually collected together in a file called a style sheet (for example
styles.css).Cascading — many style rules can apply to the same element (from the browser, from you, from different files). The cascade is the algorithm that decides which rule finally wins. We study it in detail in the chapter Specificity, Inheritance & the Cascade.
One important point for exams and interviews: CSS is not a programming language in the usual sense. You don't write step-by-step instructions, loops or branches that run in order (modern CSS does have custom properties, often called "CSS variables", and a few math functions, but no program flow). It is a declarative language: you declare what the result should look like, and the browser figures out how to draw it.
Why Do We Need CSS?
In the very early web (early 1990s), HTML pages had almost no styling. Later, browsers added presentational tags and attributes directly into HTML, such as <font>, <center> and bgcolor. Pages looked like this:
<center>
<font face="Arial" color="blue" size="5">Welcome</font>
</center>
<p><font face="Arial" color="gray">First paragraph</font></p>
<p><font face="Arial" color="gray">Second paragraph</font></p>This approach had serious problems:
Repetition: the same
<font>tag had to be repeated on every paragraph of every page.Hard maintenance: changing the brand colour from blue to green on a 200-page website meant editing 200 files.
Mixed concerns: content and decoration were tangled together, making HTML harder to read, harder for search engines and screen readers, and heavier to download.
CSS solves this with the principle of separation of concerns: HTML keeps only the content and its meaning, and all the presentation goes into CSS. The same content as above becomes:
<h1>Welcome</h1>
<p>First paragraph</p>
<p>Second paragraph</p>h1 {
font-family: Arial, sans-serif;
color: blue;
text-align: center;
}
p {
font-family: Arial, sans-serif;
color: gray;
}Now the rule "all paragraphs are gray" is written once. Add 50 more paragraphs and they are styled automatically. Change gray to black in one place and the whole site updates. (Tags like <font> and <center> are now obsolete in the HTML Living Standard — never use them.)
Benefits of CSS at a glance:
| Benefit | Why it matters |
|---|---|
| Reusability | One rule styles every matching element on every page. |
| Easy maintenance | Change the design in one file instead of hundreds of HTML files. |
| Faster pages | An external CSS file is downloaded once and cached by the browser. |
| Cleaner HTML | HTML focuses on meaning, which helps accessibility and SEO. |
| Multiple devices | The same HTML can get different layouts for mobile, desktop and print. |
Your First Styled Page
Create a file called index.html, paste the code below, and open it in any browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Styled Page</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f6fb;
margin: 40px;
}
h1 {
color: #1e3a8a;
text-align: center;
}
p {
color: #333333;
font-size: 18px;
line-height: 1.6;
}
.note {
background-color: #fff3cd;
border-left: 5px solid #f59e0b;
padding: 12px;
}
</style>
</head>
<body>
<h1>Welcome to CSS</h1>
<p>CSS controls how this page looks.</p>
<p class="note">This paragraph has a yellow background and an orange left border.</p>
</body>
</html>Output (what you see in the browser):
Page background : light grey-blue, with 40px of space around the content
"Welcome to CSS": dark blue, bold, centred
1st paragraph : dark grey text, 18px, comfortable line spacing
2nd paragraph : same text style, plus a pale-yellow box with a
thick orange stripe on its left edge and 12px of
inner space around the textNotice what happened:
The
bodyrule changed the font and background of the whole page, because the paragraphs and heading inherit the font frombody.The
h1rule only affected the heading.The
prule affected both paragraphs.The
.noterule (a class selector) affected only the paragraph withclass="note", adding to the styles it already got from theprule.
Don't worry about every property yet — each one gets its own chapter later. Here we are only learning how CSS is organised.
Anatomy of a CSS Rule
A style sheet is made of rules (also called rulesets or style rules). Every rule has the same shape:
selector
│
▼
h1 { ◄── start of declaration block
color: navy; ◄── declaration
font-size: 32px; ◄── declaration
} ◄── end of declaration block
▲ ▲
│ └── value
└── property| Part | Meaning | In the example |
|---|---|---|
| Selector | Chooses which HTML elements the rule applies to | h1 |
| Declaration block | Everything between { and } | { color: navy; font-size: 32px; } |
| Declaration | One property: value pair | color: navy; |
| Property | The feature you want to change | color, font-size |
| Value | The setting for that property | navy, 32px |
Read a rule as an English sentence: "For every h1, set the colour to navy and the font size to 32 pixels."
Syntax rules to remember
A colon
:separates the property from its value.A semicolon
;separates declarations. The semicolon after the last declaration is optional, but always write it — it prevents bugs when you add another line later.Whitespace and line breaks are ignored, so
h1{color:navy}works exactly like the formatted version. Formatting is for humans.Property names and keywords are case-insensitive (
COLOR: NAVYworks), but the convention is lowercase. Class and ID names, however, are case-sensitive:.Notedoes not matchclass="note".Some values have units (
32px,2em,50%). There must be no space between a number and its unit:32 pxis invalid. Units are covered in the chapter CSS Units.
Comments
CSS has only one comment syntax: /* ... */. It can span multiple lines.
/* Main heading style */
h1 {
color: navy; /* brand colour */
/* font-size: 40px; temporarily disabled */
}There is no // single-line comment in plain CSS. A line starting with // is not a comment; it is invalid syntax, and the browser's error recovery decides what gets thrown away. Inside a declaration block it discards everything up to the next semicolon — if the "commented" line has no semicolon, the next declaration is lost too. Outside a block it swallows the whole next rule. Sometimes it seems to "work" by luck, which makes it a very confusing bug.
How the Browser Handles Errors
Unlike a C++ or Java compiler, the browser never stops because of a CSS mistake. If it does not understand something, it simply skips that piece and continues.
p {
colour: red; /* misspelt property → this declaration is ignored */
font-size: 20px; /* still applied */
}Output: the paragraphs become 20px, but their colour does not change. No error is shown on the page — you only find it in DevTools (see below), where the bad line is struck through with a warning icon.
This "skip what you don't understand" rule is deliberate. It allows forward compatibility: a modern feature can be written after a safe fallback, and older browsers just ignore the line they don't know:
.gallery {
display: block; /* every browser understands this */
display: grid; /* browsers that support grid use this, since it comes later */
}When two declarations set the same property in the same rule, the later one wins — if the browser understands it.
How a Browser Turns HTML + CSS into Pixels
Understanding this pipeline explains a lot of CSS behaviour (and is a popular interview question).
HTML file ──parse──► DOM (tree of elements)
│
CSS files ──parse──► CSSOM (tree/collection of style rules)
│
▼
Style calculation: match selectors to elements,
run the cascade, compute final values
│
▼
Render tree (only visible elements + their styles)
│
▼
Layout: work out the size and position of every box
│
▼
Paint: fill in colours, text, borders, images
│
▼
Composite: combine layers and show on screenDOM (Document Object Model) — the browser's tree representation of the HTML.
CSSOM (CSS Object Model) — the browser's representation of all the CSS rules.
Render tree — elements that will actually be displayed. An element with
display: noneis in the DOM but not in the render tree.Layout (also called reflow) — computes geometry: widths, heights, positions.
Paint and composite — draw the pixels.
Because the page cannot be drawn correctly without knowing the styles, CSS in the <head> is render-blocking: the browser waits for it before the first paint. That is why style sheets should be small and loaded early. The next chapter, Adding CSS to HTML, discusses this further.
Browser Default Styles
Even with no CSS at all, a page is not completely plain: headings are big and bold, links are blue and underlined, and the <body> has a small margin (8px in all major browsers). These come from the browser's built-in user-agent style sheet.
So there are three possible sources of styles, and they all take part in the cascade:
| Origin | Written by | Example |
|---|---|---|
| User-agent styles | The browser | h1 is bold and large by default |
| User styles | The person using the browser | A custom style sheet or accessibility extension that enlarges text or forces high-contrast colours |
| Author styles | The web developer (you) | Your styles.css |
Your author styles normally override the browser defaults. This is why many projects start with a small "reset" or "normalize" style sheet that removes inconsistent defaults.
A Short History of CSS
| Year | Milestone |
|---|---|
| 1994 | Håkon Wium Lie proposes Cascading HTML Style Sheets while working at CERN; Bert Bos soon joins the effort. |
| 1996 | CSS Level 1 becomes a W3C Recommendation (fonts, colours, text, margins). |
| 1998 | CSS Level 2 adds positioning, media types, z-index and more. |
| 2011 | CSS 2.1 — a corrected, cleaned-up version of CSS 2 — becomes the Recommendation. |
| 2000s onward | "CSS3": instead of one big spec, CSS is split into separate modules (Selectors, Colors, Flexbox, Grid, ...), each with its own level number. |
| 2020s | Container queries, :has(), native nesting, cascade layers and subgrid arrive in all major browsers. |
There is no "CSS4". After CSS 2.1, each module evolves on its own (for example, Selectors Level 4, Color Level 4). "CSS3" today is just an informal name for "modern CSS". The CSS Working Group publishes a periodic CSS Snapshot that lists which modules are considered stable.
Checking whether a feature is safe to use
Because modules evolve independently, you should check browser support before using a new feature. A useful label you will see on MDN and caniuse.com is Baseline:
Baseline newly available — the feature works in the latest versions of all major browsers (Chrome, Edge, Firefox, Safari).
Baseline widely available — it has been newly available for at least 30 months, so it is safe even for users on slightly older browsers.
Throughout this tutorial, when we use a newer feature we will mention its support status.
What Can CSS Do?
Modern CSS is far more than colours and fonts. Here is a preview of what is coming in this tutorial:
Colours, backgrounds and gradients (Colors, Backgrounds & Gradients)
Typography and custom web fonts (Text & Fonts, Web Fonts)
Spacing and sizing of every element (The Box Model)
One-dimensional and two-dimensional page layouts (Flexbox, CSS Grid)
Layouts that adapt to phones, tablets and desktops (Responsive Design & Media Queries, Container Queries)
Reusable design values (CSS Variables)
Smooth transitions and keyframe animations — often without a single line of JavaScript
Inspecting CSS with Browser DevTools
Every modern browser has developer tools that let you see and edit CSS live. This is the single most useful habit to build while learning CSS.
Right-click any element on a page and choose Inspect (or press
F12/Ctrl+Shift+I; on macOSCmd+Option+I).In the Elements panel, the selected element is highlighted.
The Styles pane shows every rule that matches that element, with the winning rules at the top. Declarations that lost the cascade are shown with a line through them (struck through).
You can click any value to edit it, or tick/untick a checkbox to switch a declaration off, and see the result instantly. Changes are temporary and disappear on reload.
The Computed tab shows the final value of every property after the cascade.
Whenever your CSS "does not work", open DevTools first. It usually shows you exactly why: a typo (warning icon), a selector that doesn't match, or another rule that is overriding yours.
HTML vs CSS
| Point | HTML | CSS |
|---|---|---|
| Full form | HyperText Markup Language | Cascading Style Sheets |
| Purpose | Structure and meaning of content | Presentation and layout |
| Building block | Elements made of tags: <p>...</p> | Rules: selector { property: value; } |
| File extension | .html | .css |
| Can work alone? | Yes — a plain page with default styles | No — it needs a document to style |
| Error handling | Browser repairs bad markup | Browser ignores invalid declarations/rules |
Common Mistakes
Forgetting the semicolon:
color: red font-size: 20px;makes the browser read one broken declaration, so both are ignored.Using
//for comments: only/* */is valid in CSS.Space between number and unit:
20 pxis invalid; write20px.Using
=instead of:, e.g.color = red;— this is invalid and ignored.Wrong case in class names:
.Cardwill not matchclass="card".Using HTML for presentation: picking
<h3>just because "it's the right size" or using<br>for spacing. Choose HTML elements by meaning; adjust their look with CSS.
Interview / Exam Questions
1. What is CSS and why is it called "cascading"?
CSS (Cascading Style Sheets) is a declarative style sheet language that describes how HTML (or XML) documents are presented. It is called cascading because several rules from different sources (browser defaults, user settings, author style sheets) may apply to the same element; the cascade algorithm resolves these conflicts using origin and importance, specificity and source order to pick a winning value.
2. Name the parts of the rule p { color: red; }
p is the selector; { color: red; } is the declaration block; color: red; is a declaration; color is the property and red is the value.
3. What happens if a CSS declaration contains an unknown property?
The browser ignores (drops) that declaration only and continues parsing the rest of the rule and style sheet. No error is displayed on the page. This allows fallbacks: a widely supported declaration can be followed by a newer one, and older browsers ignore what they don't understand.
4. Is there a CSS4?
No. After CSS 2.1, CSS was divided into independent modules, each with its own level (for example Selectors Level 4 or Color Level 4). "CSS3" is just a popular label for modern CSS, and there is no single "CSS4" specification.
5. Why is CSS called render-blocking?
The browser needs the CSSOM to know how elements should look before it can build the render tree and lay out the page. So it delays the first paint until style sheets in the <head> are downloaded and parsed. This avoids showing unstyled content that then jumps around.
6. An element has display: none. Is it in the DOM? In the render tree?
It is in the DOM (it still exists in the HTML and can be accessed by JavaScript), but it is not in the render tree, so it takes no space and is not painted.
Summary
CSS describes the presentation of HTML documents: colours, fonts, spacing, layout, animation.
It keeps content (HTML) separate from presentation (CSS), making sites easier to maintain and faster to load.
A rule = selector + declaration block; each declaration is
property: value;.Comments use
/* */only. Invalid declarations are silently ignored, which enables fallbacks.The browser builds the DOM and CSSOM, computes styles, does layout, then paints.
Styles come from the browser, the user and the author; the cascade decides the winner.
There is no CSS4 — CSS evolves module by module. Check Baseline status before using new features.
In the next chapter, Adding CSS to HTML, we will see the three ways of connecting CSS to a page and when to use each one.