Adding CSS to HTML
CSS controls how HTML looks. There are three ways to attach it — an external stylesheet, a <style> element, and the style attribute — and each has its place. This lesson covers all three and the basics of how CSS targets HTML.
1. External stylesheets (recommended)
<title>My site</title> <link rel="stylesheet" href="css/styles.css">
body {
font-family: system-ui, sans-serif;
line-height: 1.6;
max-width: 65ch;
margin: 0 auto;
padding: 1rem;
}
h1 {
color: #d6336c;
}
A separate .css file can style every page on the site, so one edit updates them all. The browser caches it, making later pages load faster. This is the standard approach for real sites.
2. Internal styles
A <style> element (normally in the head) is handy for single-page demos, page-specific tweaks, and small amounts of critical CSS that should render instantly.
3. Inline styles
The style attribute applies CSS to one element. It's useful for values set by JavaScript or generated per item (like a progress bar's width), but avoid it for general styling: it can't be reused, mixes presentation into content, overrides other rules, and can't use media queries or hover states.
How CSS selects HTML
A CSS rule picks elements with a selector, then sets properties on them:
| Selector | Matches |
|---|---|
p | Every <p> element |
.highlight | Elements with class="highlight" |
#intro | The element with id="intro" |
nav a | <a> elements inside a <nav> |
a:hover | Links being hovered over |
input[type="email"] | Inputs with that attribute value |
Good HTML — semantic elements and meaningful class names — makes writing CSS far easier.
The cascade, briefly
When several rules set the same property on an element, the browser decides which wins by:
- Importance —
!importantdeclarations win (use rarely). - Specificity — inline styles beat ids, ids beat classes, classes beat element names.
- Order — if all else is equal, the rule that comes last wins.
That's why the order of <link> tags matters: put your own stylesheet after any framework's stylesheet so yours can override it. The CSS course covers the cascade in depth.
Media attributes
<title>Styles</title> <link rel="stylesheet" href="print.css" media="print"> <link rel="stylesheet" href="wide.css" media="(min-width: 900px)">
A media attribute applies a stylesheet only in matching conditions — for printing, or for wide screens.
Browser default styles
Even without any CSS, browsers apply default styles: headings are bold and large, links blue and underlined, lists indented. Many projects start with a small "reset" or "normalize" stylesheet to make these defaults consistent across browsers before adding their own design.