Sub topic 10
Loading CSS from CSS with @import
This chapter assumes you can already attach CSS with the style attribute, a style element, and a link element. It also assumes you know how the cascade picks a winner when rules overlap. You should be comfortable with relative file paths. Here you will learn what @import does, where it can go, how it affects the cascade, and why it is usually the wrong choice for a page's main stylesheets.
What @import does
@import is a CSS at-rule that tells the browser to fetch another stylesheet and apply its rules as if they were written at that spot. The rule works from inside a CSS file or a style element. It cannot go in a style attribute, because an attribute holds only declarations, not rules.
The spine example uses this file:
/* main.css */
@import url("reset.css");
body {
margin: 0;
}When the browser parses main.css, it sees the import, requests reset.css, and treats that file's rules as sitting where the @import line is. The body rule that follows is evaluated after them.
You can write the target as a url() function or as a plain string. Both forms are equivalent:
@import url("reset.css");
@import "reset.css";Always end the rule with a semicolon. If you forget it, the browser may swallow the next line into the import and silently drop it.
Resolving paths
A relative path inside an @import is resolved against the location of the stylesheet that contains the rule. It is not resolved against the HTML page. This differs from the href on a link element, which is resolved against the page.
Suppose the project looks like this:
site/
index.html
css/
main.css
reset.css
components/
buttons.cssThe page links only css/main.css:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Imports</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<button class="btn">Save</button>
</body>
</html>Inside css/main.css, the imports are written relative to the css folder:
/* css/main.css */
@import url("reset.css");
@import url("components/buttons.css");
body {
font-family: system-ui, sans-serif;
}Writing css/reset.css here would fail. The browser would look for css/css/reset.css and get a 404 error. A failed import is skipped quietly, and the rest of the sheet still applies. So the symptom is missing styles, not a visible error. Check the Network panel in developer tools when styles go missing.
Placement rules
@import must come before every other rule in the stylesheet. Only @charset and @layer statements (the form with names and no block) may appear before it. An import that comes after a normal rule is ignored.
/* This works */
@import url("reset.css");
body {
margin: 0;
}
/* This import is ignored: it follows a style rule */
@import url("theme.css");Comments are allowed anywhere, so a comment before the import does no harm. In a style element, the same rule applies. The first thing inside the element must be the imports:
<style>
@import url("css/reset.css");
p { color: darkblue; }
</style>Conditions on an import
After the URL you can add conditions. The import loads only if they match, and its rules apply only under those conditions. The order is fixed: URL, then layer(), then supports(), then a media query list.
@import url("print.css") print;
@import url("wide.css") screen and (min-width: 60rem);
@import url("grid.css") layer(layout) supports(display: grid);- A media query list works like the
mediaattribute on alinkelement. The first line is the CSS counterpart of theprint.cssexample from thelinkelement section. layer(name)places the imported rules into a named cascade layer. Layers have their own precedence order, which is covered with the cascade material. Here it is enough to know that@importis the way to put a whole file into a layer.supports(condition)loads the file only if the browser understands the given feature. Older browsers do not understand this syntax and skip the import. If the file must always load, do not addsupports().
A matching condition does not guarantee the browser skips the download when it does not match. Browsers may still fetch such files at a lower priority. Treat conditions as controlling application of the rules, not as a bandwidth optimization.
How imports interact with the cascade
An import behaves as if the file's contents were pasted at the import line. This has three consequences.
First, rules later in the importing file beat imported rules when specificity is equal. That makes imports a natural place for defaults:
/* reset.css */
p { margin: 0; color: black; }/* main.css */
@import url("reset.css");
p { color: darkgreen; }Paragraphs are dark green, because main.css sets color after the import with the same specificity. The margin: 0 from the reset still applies, because nothing overrides it.
Second, order among several imports follows their order in the file. If a.css and b.css both set h1 { color: ... }, the one imported later wins.
Third, imports do not change specificity. An imported #header p rule beats p in the main file regardless of order. Source order only breaks ties. Inline styles and !important behave the same as with any other stylesheet.
The performance cost
The main reason to avoid @import for a page's own styles is the loading sequence. With link elements, the browser sees all of them while parsing the HTML head and can request the files in parallel. With @import, the browser cannot know about the second file until it has downloaded and parsed the first one.
CSS in the head blocks rendering. The browser avoids painting unstyled content, so it waits for the stylesheets it knows about. Each level of import adds a full network round trip before the page can render. On a slow connection, with a chain of three or four imports, that delay is easy to notice.
Compare the alternative, where the HTML lists every file:
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/main.css">Both requests start at once, and the cascade order is the same as long as the link elements appear in the order the imports would have had. This gives the same result with less waiting.
Caching is not the problem here. Imported files are cached like any other stylesheet, according to their own response headers. The cost is the discovery delay, not repeat visits.
Other gotchas
- Import cycles. If
a.cssimportsb.cssandb.cssimportsa.css, the browser detects the loop and ignores the repeat. Do not rely on this. Cyclic imports usually mean the files are split in the wrong places. - Duplicate imports. If two files import the same stylesheet, the browser may apply its rules at both positions. The second occurrence can override rules that came between them. Keep the import graph a tree, not a web.
- Content Security Policy. A
style-srcpolicy applies to imported files too. Withstyle-src 'self', importing from another origin is blocked. - Failure is silent. A wrong path, a misplaced import, or a missing semicolon all produce no page-level error. Look in the Network panel for a red request, and in the Styles pane for a rule that never appears.
- Preprocessor confusion. Sass and similar tools also have an
@importor@usefeature that merges files at build time. That is a different mechanism. The compiler inlines the files, and the browser never sees an import. Plain CSS@importis the one that causes extra requests at run time.
When @import is reasonable
For most pages, prefer separate link elements or one bundled file produced by a build tool. @import earns its place in a few cases:
- Layering third-party CSS.
@import url("vendor.css") layer(vendor);lets you rank an entire library below your own rules without editing it. - A small stylesheet loaded from a
styleelement in a page where you cannot edit theheadlinks, such as a content system that gives you only an inline style block. - Prototypes and teaching examples, where simplicity matters more than load time.
- Conditional features where
supports()and a media list in one line is clearer than extra markup.
If you import in production, keep the chain to one level. The page links main.css, and main.css imports the others. Never import a file that itself imports more files.
Checking your work
To confirm an import loaded, open developer tools and look at the Network panel filtered to CSS. The imported file should appear, and its "initiator" column should name the stylesheet that imported it. In the Elements panel, rules from the imported file show the imported file's name beside each rule in the Styles pane. If the file is listed in red with a 404 status, fix the path using the resolution rule above.
Exercise
A page links css/main.css. That file contains @import url("css/reset.css"); and the reset never applies. The files are css/main.css and css/reset.css. What is wrong, and what is the fix?
Show answer
The path is resolved against the location of main.css, which is already in the css folder, so the browser requests css/css/reset.css and gets a 404. Change the import to @import url("reset.css");.
Exercise
You have p { color: darkgreen; } followed by @import url("theme.css");, and theme.css sets p { color: purple; }. Which color do paragraphs get, and why?
Show answer
Dark green, because the import is ignored. It follows a style rule, and @import must come before all other rules except @charset and @layer statements. If you move the import to the top, the p rule after it wins on source order and paragraphs are still dark green.
Exercise
Why does a chain of @import rules usually load slower than the same files listed as link elements?
Show answer
The browser finds link elements while parsing the HTML and requests the files in parallel. It finds an @import only after downloading and parsing the stylesheet that contains it, so each level of import adds a round trip before rendering.