Sub topic 5
External styles: linking a stylesheet
An external stylesheet is a separate .css file that an HTML page loads with a <link> element. Many pages can point at the same file. Changing one rule then changes every page that uses it. This chapter covers how to link a stylesheet, how the browser resolves the file path, and what usually goes wrong.
Prerequisites
This chapter assumes you can:
- Write a basic HTML document with
html,head, andbody. - Save text files and open them in a browser.
- Read a file path such as
css/site.cssor../img/logo.png.
You should also know the rule syntax from the earlier chapters: a selector, then braces holding property: value; declarations.
The working model
When the browser parses your HTML and reaches a <link rel="stylesheet"> element, it takes these steps:
- It reads the
hrefvalue and resolves it into a full URL, using the page's own URL as the base. - It requests that URL, from the network, from its cache, or from disk.
- It parses the response as CSS.
- It applies the rules to the matching elements in the page.
The stylesheet is a separate resource. The HTML file does not contain it, and the browser can store it, reuse it, and download it independently of the page.
The link element
A minimal working example has two files. The HTML page comes first.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>External styles</title>
<link rel="stylesheet" href="css/site.css">
</head>
<body>
<h1>Welcome</h1>
<p>This page gets its styles from css/site.css.</p>
</body>
</html>The stylesheet goes in css/site.css.
/* css/site.css */
body {
font-family: system-ui, sans-serif;
margin: 2rem;
}
h1 {
color: darkgreen;
}
p {
line-height: 1.5;
}The <link> element is a void element. It has no closing tag and no content. Two attributes matter in almost every case:
rel="stylesheet"tells the browser what kind of resource this is. Without it, the browser does not treat the file as a stylesheet.hrefis the location of the file.
You may see type="text/css" in older code. It is unnecessary in HTML5 and you can leave it out.
Place <link> in the <head>. Browsers also accept it in the body. But a stylesheet that is discovered late can make the page render unstyled and then change its appearance, so the head is the conventional place.
What belongs in the CSS file
The file contains CSS and nothing else. It has no <style> tags, no <html>, and no other markup. Comments use /* ... */.
This is wrong:
<style>
p { color: red; }
</style>The browser reads <style> as part of the first selector, so the first rule breaks and is skipped. CSS parsers recover from errors by dropping the broken rule and continuing. A rule can therefore fail without any visible error message.
Writing the href correctly
The href resolves against the URL of the HTML page, not against the CSS file and not against your project root. The browser accepts several forms.
| Form | Example | Resolves to |
|---|---|---|
| Relative to the page | `css/site.css` | The `css` folder next to the HTML file |
| Parent folder | `../css/site.css` | One folder up, then `css` |
| Root-relative | `/css/site.css` | The `css` folder at the site root |
| Absolute URL | `https://example.com/css/site.css` | That exact address |
Suppose your project looks like this:
project/
index.html
css/
site.css
blog/
post.htmlindex.html uses href="css/site.css". blog/post.html is one folder deeper, so it needs href="../css/site.css". If you copy the head from one page into the other without changing the path, the link breaks on the second page.
A root-relative path starts with / and avoids this problem, because it means the same thing from any page. It only works when the site is served from a web server. If you open files straight from disk, /css/site.css points at the root of your drive and fails.
Paths inside the CSS file
Some declarations inside a stylesheet contain their own URLs, such as url() for images or fonts. These resolve relative to the stylesheet's location, not the page's.
/* css/site.css */
body {
background-image: url("../img/pattern.png");
}The file css/site.css lives one folder below the project root. The path ../img/pattern.png therefore goes up to project/ and then into img/. This holds for every page that uses the stylesheet, whatever folder the page is in. That is why the same CSS file works from both index.html and blog/post.html.
Using several stylesheets
A page can contain more than one <link>:
<link rel="stylesheet" href="css/base.css">
<link rel="stylesheet" href="css/layout.css">
<link rel="stylesheet" href="css/blog.css">The browser fetches them in parallel and applies them as if they were one long stylesheet, in the order the <link> elements appear. If two rules have equal specificity and set the same property, the later one wins. The next chapter covers this in detail. For now, remember that the order of your <link> elements matters.
A common split is a shared file for every page and a smaller file for one section of the site. The section-specific file goes last so that it can override the shared one.
Restricting a stylesheet with media
The optional media attribute applies a stylesheet only when the condition matches.
<link rel="stylesheet" href="css/site.css">
<link rel="stylesheet" href="css/print.css" media="print">
<link rel="stylesheet" href="css/wide.css" media="(min-width: 900px)">Here print.css applies only when the page is printed or shown in a print preview. wide.css applies only in windows at least 900 pixels wide. The browser may still download a non-matching stylesheet, but it does not apply it, and it does not let it delay the first display of the page. Without a media attribute, the default is all.
Why teams use external stylesheets
External files are the usual choice for anything beyond a throwaway page, for these reasons:
- Reuse. One file styles every page, so the look of the site stays consistent.
- Maintenance. Changing the heading color means editing one line in one file.
- Caching. After the first visit, the browser can keep
site.cssand reuse it on later pages without downloading it again. Styles inside a<style>element or astyleattribute are part of the HTML and are downloaded again each time the HTML is. - Separation. HTML describes the content. CSS describes how it looks. Each file is shorter and easier to read.
The cost is one extra request on the first visit. Later chapters cover the performance and security details, including how a linked stylesheet can delay rendering.
Common errors
The styles do not apply at all
Check these causes in order:
- Wrong path. This is the most frequent cause. A typo, a wrong folder level, or a wrong file name makes the request fail. The browser shows no error on the page. The page just looks unstyled. Open the developer tools, look at the Network panel, and check whether
site.csshas a 404 status. - Missing
rel="stylesheet". Without it, the file is not loaded as a stylesheet. - Wrong attribute name. Writing
src="css/site.css"instead ofhrefdoes nothing.<link>useshref. - Unsaved or wrong file. You edited a copy in another folder, or you did not save.
The file name is right on your machine but fails on the server
Many servers run on Linux, where file names are case-sensitive. Site.css and site.css are different files. Windows and macOS usually ignore the difference locally, so the bug appears only after deployment. Pick one convention, such as all lowercase with hyphens, and keep to it.
The server sends the wrong content type
A server tells the browser what a file is through the Content-Type response header. For stylesheets it should be text/css. In standards mode, a browser can refuse a stylesheet delivered with another type, such as text/html. This happens, for example, when a misconfigured server returns an HTML error page at the CSS address. Local files and common web servers get this right, but custom servers sometimes do not.
Your edits do not show up
The browser may be using a cached copy of the old file. Reload the page without the cache (usually Ctrl+Shift+R or Cmd+Shift+R), or turn on "Disable cache" in the Network panel while developing. In production, sites often add a version to the URL, such as href="css/site.css?v=3", so that a changed URL forces a fresh download.
Only part of the stylesheet works
If the first few rules apply and later ones do not, look for a syntax error just before the first rule that fails. A missing closing brace or a missing semicolon can cause the browser to discard the next rule too.
Checking your understanding
Exercise
A page at /blog/post.html contains <link rel="stylesheet" href="css/site.css">, and the stylesheet is at /css/site.css. The page is unstyled. Give two different corrected href values that fix it, and say what one background-image: url("../img/bg.png") inside /css/site.css points to.
Show answer
The page resolves href against /blog/, so it requests /blog/css/site.css, which does not exist. Two fixes are href="../css/site.css" (relative, one level up) and href="/css/site.css" (root-relative, which works when served from a web server). The url("../img/bg.png") inside the stylesheet resolves against the stylesheet's own location, /css/, so it points to /img/bg.png.
Exercise
You change a color in site.css and save it, but the browser still shows the old color. The path is correct and the Network panel shows the file loading. Name the most likely cause and two ways to deal with it.
Show answer
The browser is using a cached copy of site.css. During development, do a hard reload (Ctrl+Shift+R or Cmd+Shift+R) or enable "Disable cache" in the Network panel. For deployed sites, change the URL when the file changes, for example href="css/site.css?v=4", so the browser fetches the new version.