Lesson 2 of 50
cssAdding CSS to a Page
7 mins
Course progress4%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 2 of 50
css7 mins
Keep these ideas in mind as you work through the lesson.
There are three ways to attach CSS to an HTML document. Each has trade‑offs in performance, maintainability and specificity.
| Method | Syntax | When to use | Pros | Cons |
|---|---|---|---|---|
| Inline | <p style="…"> | Quick prototyping or dynamically generated styles from JS. | Highest specificity, no extra request. | Hard to maintain, breaks cascade, not cacheable. |
| Embedded | <style> … </style> inside <head> | Critical CSS that must load before the page paints. | No extra HTTP request, can be inlined by build tools. | Still part of the same file, grows the HTML size. |
| External | <link rel="stylesheet" href="style.css"> | Site‑wide visual rules, libraries, theme files. | Cached by the browser, keeps HTML lean, easy to edit. | Extra network request unless preloaded. |
The golden rule for production sites: external stylesheet + critical‑CSS inlining.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/css/main.css" />
<title>My Site</title>
</head>
<body>
<!-- page markup -->
</body>
</html>
<link rel="preload" href="/css/main.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/css/main.css"></noscript>
Preloading tells the browser to fetch the CSS early while still keeping it non‑blocking. Once loaded the
onloadhandler swaps therelattribute, turning the resource into a normal stylesheet.