2.1 What Is CSS: Three Ways to Apply It
In the last chapter we built the page skeleton with HTML, but it looks plain: black text, white background, default font. CSS (Cascading Style Sheets) is what makes it beautiful — colors, sizes, spacing, layout, all come from CSS.
An analogy: if HTML is a house's bare structure (where the walls and doors are), CSS is the decoration (what color to paint, what wallpaper to hang, how to arrange the furniture).
What a CSS rule looks like
A CSS rule has two parts: a selector (who to pick) and a declaration block (how to change them):
h1 {
color: blue;
font-size: 32px;
}h1is the selector: "all h1 elements."
- Inside the braces are declarations: each is
property: value;, like setting the color to blue and the size to 32 pixels.
- Don't forget the semicolon
;at the end of each declaration.
Three ways to attach CSS to a page
The lab below lets you switch between the three ways, and you'll see they produce the identical result — the only difference is where the code lives.
1. Inline — written directly in a tag's style attribute:
<p style="color: red; font-weight: bold;">A red, bold line</p>It affects only this one element. Quick to write, but no reuse, and it has the highest priority (it can override other styles, which makes debugging harder).
2. Internal — written in a <style> tag inside <head>:
<head>
<style>
p { color: red; }
</style>
</head>It applies to every <p> on the page. Fine for a small single-page project.
3. External — a separate .css file linked with <link> (most recommended):
<head>
<link rel="stylesheet" href="styles.css">
</head>/* styles.css */
p { color: red; }Why external stylesheets are recommended
- Reuse: one
.cssfile can be shared by many pages — edit once, update the whole site.
- Clear separation: HTML handles content, CSS handles style; cleaner code.
- Caching: the browser caches the
.cssfile, so other pages don't re-download it.