Adding CSS to a Page: link, style, @import and Inline Styles
The four ways to connect CSS to HTML: external stylesheets with link, embedded style elements, @import with layers and conditions, and inline style attributes, plus the media attribute, loading order, alternate stylesheets and which method to use when.
kvi5hnuCode Sprout team member13 min readOn this page
A stylesheet does nothing until a document uses it. HTML gives you four ways to connect them: an external file loaded with <link>, a <style> element inside the page, @import rules that pull one stylesheet into another, and style attributes on individual elements. They all feed into the same cascade, but they differ in caching, loading speed and how easy they are to maintain. This article covers each one and when to use it.
The example page
Most examples in this course style parts of Harbor Books, a small independent bookshop's website: a header with navigation, cards for featured books, an events list and a newsletter form. Here's a minimal version of its home page with all four connection methods in use:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Harbor Books</title>
<!-- 1. external stylesheet -->
<link rel="stylesheet" href="/css/site.css">
<!-- 2. embedded stylesheet -->
<style>
/* 3. @import must come before any other rule */
@import url("/css/print.css") print;
.hero { background: #f4efe6; }
</style>
</head>
<body>
<!-- 4. inline style -->
<h1 style="color: #8a3b12">Harbor Books</h1>
<p class="hero">New releases every Tuesday.</p>
</body>
</html>
External stylesheets with <link>
An external stylesheet is a plain-text file, usually ending in .css, that contains only CSS: rules and comments, with no HTML tags. A <link> element in the page's <head> loads it:
<link rel="stylesheet" href="/css/site.css">
rel="stylesheet"is required. It tells the browser what the linked file is for. Without it, nothing is applied.hrefis the file's URL, absolute (https://cdn.example.com/site.css) or relative to the page (css/site.css,/css/site.css).type="text/css"is optional. CSS is the default, so modern pages leave it out.medialimits the stylesheet to certain media or conditions, such asmedia="print"ormedia="(width >= 60em)". The default isall.
You can link as many stylesheets as you like. The browser combines their rules into one cascade, and when two rules conflict with the same importance and specificity, the one that comes later wins, so the order of the <link> elements matters (article 17).
<link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="/css/components.css">
<link rel="stylesheet" href="/css/print.css" media="print">
External stylesheets are the right default for a website:
- One file styles every page. Change the file, and the whole site changes.
- The browser caches it. After the first page, other pages reuse the downloaded file.
- Content and presentation stay separate, which makes both easier to maintain.
Loading and render blocking
A stylesheet in the <head> is render-blocking: the browser doesn't paint the page until it has downloaded and parsed it. That's deliberate. Painting first would show unstyled content and then jump, which is called a flash of unstyled content (FOUC). The cost is that a slow stylesheet delays the whole page, so keep critical CSS small and served quickly.
A stylesheet with a media value that doesn't match, such as media="print" on a screen, is still downloaded, but at a low priority, and it doesn't block rendering.
To load a stylesheet that isn't needed for the first screen without blocking rendering, two patterns are common: <link rel="preload" href="extra.css" as="style"> to start the download early and apply it later with a script, or a stylesheet with media="print" whose onload handler switches media to all. The opposite also exists: blocking="render" on a <link>, <style> or <script> makes the browser wait for it before the first paint (Chromium and Safari 18.2+).
Stylesheets from a CDN can carry Subresource Integrity: <link rel="stylesheet" href="https://cdn.example/lib.css" integrity="sha384-..." crossorigin="anonymous">. If the file's hash doesn't match, the browser refuses it, which protects you if the CDN is compromised.
The <link> element can also appear in <body>. Browsers apply it when they reach it, and content after it waits until it loads. Some sites use that to load a component's styles just before the component, but most keep stylesheets in the head.
Alternate stylesheets
HTML defines alternate stylesheets, which users can switch to:
<link rel="stylesheet" href="default.css" title="Default">
<link rel="alternate stylesheet" href="large-print.css" title="Large print">
The title attribute has a side effect worth knowing. A stylesheet with rel="stylesheet" and no title is persistent: it always applies. Giving it a title makes it preferred, and only one preferred set applies at a time: if several <link> elements have different titles, the browser uses one set and ignores the others. So don't add title to ordinary stylesheet links. (Links that share the same title form one set: a theme can have a screen and a print stylesheet, both titled "Large print", that switch together.)
Only Firefox offers a menu for choosing alternate stylesheets (View > Page Style). Chromium-based browsers and Safari ignore them, so sites that offer themes use a script or the prefers-color-scheme media feature instead (article 34).
Embedded stylesheets with <style>
A <style> element holds CSS directly in the HTML page. It's called an embedded or document stylesheet:
<style>
.hero { background: #f4efe6; padding: 2rem; }
</style>
It normally goes in the <head>, but <style> in the <body> also works in every browser and is valid HTML. Like <link>, it accepts a media attribute: <style media="print"> applies only when printing.
Embedded styles are useful for:
- Single-page documents and demos, where a separate file adds nothing.
- Critical CSS: the small set of rules needed for the first screen, inlined so the page can render without waiting for a download, while the full stylesheet loads.
- Page-specific styles that no other page needs.
Every live example in this course is a playground with separate HTML and CSS tabs, and sometimes JavaScript. The page it builds is exactly this: the CSS as an embedded stylesheet in the <head>, then the HTML. Edit either, and the preview updates:
h1 {
color: #8a3b12;
font-family: Georgia, serif;
}
.hero {
background: #f4efe6;
padding: 1rem;
border-left: 4px solid #8a3b12;
}
The preview is an empty page with no styles of its own, so you see the browser's defaults wherever the example doesn't override them, such as the serif font of the paragraph and the 8px margin around the page.
@import: stylesheets that load stylesheets
An @import rule loads another stylesheet from inside a stylesheet, either a .css file or a <style> element:
@import url("reset.css");
@import "typography.css"; /* url() is optional */
@import url("print.css") print; /* only for print */
@import url("wide.css") (width >= 60em);
The rules:
- Imported rules count as if they were written where the
@importis, that is, before the importing stylesheet's own rules. So when an imported rule and a rule of the importing sheet tie, the importing sheet's rule wins. @importmust come first. Only@charsetand@layerstatements may come before it. An@importafter any other rule is ignored.- Media conditions after the URL work like the
mediaattribute of<link>. layer()puts the imported rules in a cascade layer, which is the main reason to use@importtoday:@import url("vendor.css") layer(vendor);(article 20). A barelayer, with no name, puts them in an anonymous layer.supports()imports the file only if the browser supports a feature:@import url("grid-layout.css") supports(display: grid);. Thesupports()condition works in all major browsers since 2024 (Safari 17.5).
The parts have a fixed order: the URL, then layer(), then supports(), then the media query. Written in another order, the browser reads the rest as an invalid media query, and the file isn't applied at all: @import url("a.css") screen layer(base); loads nothing.
@layer reset, vendor, components;
@import url("reset.css") layer(reset);
@import url("datepicker.css") layer(vendor) supports(selector(:has(a)));
Why @import is slow
When the browser parses site.css and finds @import url("reset.css"), it only then starts downloading reset.css. If reset.css imports another file, that's a third round trip. These downloads happen one after another, while separate <link> elements download in parallel, as soon as the browser reads the HTML.

So in production, prefer several <link> elements, or a build tool that combines the imports into one file (article 120). @import is fine during development, inside a build pipeline, and when you need layer() for third-party CSS you can't edit.
Inline styles with the style attribute
The style attribute holds declarations for a single element, without a selector or braces:
<p style="color: #555; font-style: italic">Closed on public holidays.</p>
Inline styles have real drawbacks:
- They apply to one element only, so the same values are repeated across pages and are hard to change.
- They beat almost every stylesheet rule (article 17): only
!importantdeclarations in a stylesheet, and running animations, override them. That makes them hard to override later, such as in a media query or a dark theme.
The middle panel shows why inline styles are hard to override, and the right one shows the only stylesheet declarations that beat them.
- They can't use selectors, pseudo-classes, pseudo-elements or media queries. You can't write a
:hoverstyle or a mobile layout inline. - A strict Content Security Policy blocks them unless the policy allows
'unsafe-inline'styles.
There is one good modern use: setting a custom property that a stylesheet then uses (article 27). The value is data, which belongs with the element, and the design stays in the stylesheet:
.stock {
height: 1rem;
width: calc(var(--level) * 1%);
background: #2f7d4f;
margin-bottom: 0.5rem;
}
Inline styles also appear when JavaScript changes element.style, as in el.style.setProperty('--level', 50), and in HTML email, where many email programs ignore <style> elements.
Other ways styles arrive
- The
LinkHTTP header. A server can sendLink: </css/site.css>; rel=stylesheetin its response. Only Firefox applies stylesheets sent this way, so don't rely on it. The same header withrel=preloadis widely used to start downloads early. - Constructable stylesheets. JavaScript can create a stylesheet with
new CSSStyleSheet()and add it todocument.adoptedStyleSheets, or to a shadow root, which is how many web components share styles (article 14). - The browser itself. Every browser has a user-agent stylesheet with default styles, such as margins on
<body>and<p>, bold<strong>and blue underlined links. Users can add their own styles too, through browser settings or extensions. These are the other origins in the cascade (article 17). - Presentational HTML attributes such as
widthon<img>andbgcoloron old tables act like low-priority styles. Modern HTML keepswidthandheighton images and videos because they let the browser reserve space before the image loads (article 38), but use CSS for everything else.
Which method to use
| Method | Use it for | Avoid it for |
|---|---|---|
<link> | a site's stylesheets: cached, parallel, maintainable | nothing; it's the default |
<style> | critical CSS, single pages, demos, page-specific rules | large shared styles, which can't be cached across pages |
@import | development, layering third-party CSS with layer() | production loading chains |
style attribute | passing values as custom properties, values set by script, HTML email | regular styling |
What's current
@importwithsupports()works in Chromium, Firefox and Safari since 2024. Older browsers ignore the whole@importrule when they don't understand the condition.@import ... layer()has been supported everywhere since 2022.<style>and<link>in<body>are valid HTML. Browsers treat them consistently, but stylesheets in the head are still the norm.- Blocking
@importchains remain slow in every browser. HTTP/2 and HTTP/3 make each request cheaper, but they don't remove the wait for one file before discovering the next.
Common questions
My stylesheet isn't applied at all. What should I check first?
Open DevTools' Network panel and reload. If the file shows a 404, the href is wrong: relative URLs are resolved against the page, not your project folder. If it loads but isn't applied, check that rel="stylesheet" is present and spelled correctly, that the server sends it as text/css (browsers reject CSS files served with another type, such as text/plain), and that there's no media value that doesn't match. Article 4 shows how to check which rules apply.
Is <style> in the <body> valid?
Yes. HTML allows it, and every browser applies it. The styles apply to the whole document, not just the elements after it. Content above it may be painted before it's parsed, so styles that change the first screen belong in the head.
Why does my @import do nothing?
It probably comes after another rule. @import must be at the top of the stylesheet, after only @charset and @layer statements. Anything else before it, even a single rule, makes the browser ignore it. Also check that the URL is relative to the stylesheet, not to the page: inside /css/site.css, @import "reset.css" loads /css/reset.css.
How do I override a style set by an inline style attribute?
Only an !important declaration in a stylesheet (or a running CSS animation) beats an inline style without !important. If you control the page, remove the inline style or replace it with a class. If it comes from a script or a third-party widget, a rule with !important is the practical fix (article 17).
Should I put all CSS in one big file or many small ones? For the browser, fewer requests used to be much better. With HTTP/2 and later, several moderately sized files are fine, and splitting by page or component can help caching. Organize your source in as many files as you like and let a build tool decide how to bundle them (article 120).
Do I need type="text/css"?
No. It's the default for both <link rel="stylesheet"> and <style>. You'll see it in older code, and it's harmless.
Summary
<link rel="stylesheet" href="...">loads an external stylesheet. It's cached, downloads in parallel and is the default for websites.<style>embeds CSS in the page, which suits critical CSS, demos and page-specific rules.@importloads a stylesheet from another stylesheet. It must come first, can take media conditions,layer()andsupports(), and chains of imports load one after another.- The
styleattribute styles one element, beats normal stylesheet rules, and can't use selectors or media queries. Its best use is passing custom property values. - Stylesheets in the head block rendering until they load, which prevents unstyled content from flashing.
- The browser's own stylesheet, user styles and presentational HTML attributes also take part in the cascade.
Practice questions
A page links two stylesheets in this order, and both set the h1 color with the same selector. Which color wins, and why?
<link rel="stylesheet" href="a.css">
<link rel="stylesheet" href="b.css">
Answer
The color from b.css. The two rules have the same origin, importance and specificity, so the cascade falls back to order of appearance, and b.css comes later in the document.
This stylesheet's import has no effect. Why?
body { margin: 0; }
@import url("fonts.css");
Answer
@import must come before every other rule except @charset and @layer statements. Because body { margin: 0; } comes first, the browser ignores the @import. Move it to the top.
Why can't you write a hover style in a style attribute?
Answer
A style attribute contains only declarations for that element. It has no selector, so it can't use pseudo-classes such as :hover, pseudo-elements such as ::before, or media queries. Put those rules in a stylesheet. The inline attribute can still set a custom property that the hover rule uses.
Your site's main.css imports layout.css, which imports grid.css. Why does this slow the first page load, and what's the fix?
Answer
The browser discovers each file only after downloading and parsing the previous one, so the three files download one after another. Link the files separately with <link> elements, which the browser finds in the HTML and downloads in parallel, or bundle them into one file with a build tool.
A teammate adds title="Main" to the site's only <link rel="stylesheet">, and nothing changes. Later, they add a second stylesheet with title="Extras", and its rules never apply. Why?
Answer
A title turns a persistent stylesheet into a preferred one, and only one preferred set applies at a time. With two different titles, the browser picks one set and ignores the other. Remove the title attributes so both stylesheets are persistent.
Previous: What CSS Is: Styling Documents, Standards, Browsers and Baseline
Next: CSS Syntax: Rules, Declarations, Comments, and How Browsers Handle Errors

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.