CSS Reference ยท At-rules
The @import at-rule
Reference for the CSS @import at-rule: load another stylesheet, attach media queries, layers and supports conditions, and avoid its performance traps.
The @import at-rule pulls the rules of another stylesheet into the current one. The imported sheet is treated as if it were written at that position, so the order of imports affects the cascade.
An import must come before every other rule in the stylesheet, except @charset and @layer statements (the form that only declares layer names). An import placed later is silently ignored.
@import url("base.css"); @import "theme.css" layer(theme) screen and (min-width: 40rem);
Try it
This example imports a tiny stylesheet from a data: URL, because the preview cannot reach other files.
Syntax
@import <url> [ layer | layer(<name>) ]? [ supports(<condition>) ]? <media-query-list>?; @import "print.css" print; @import url("fonts.css") layer(vendor) supports(display: grid);
- URL: a quoted string or
url(); relative URLs resolve against the stylesheet that contains the@import, not the HTML page. layer: puts the imported rules into a cascade layer (anonymous with the bare keyword).supports(): import only if the condition passes.- Media queries: import only for matching media.
- All parts go before the semicolon, in that order.
Values
| Syntax and arguments | Description |
|---|---|
"file.css" / url(file.css) |
The stylesheet to load. |
layer(name) |
Wrap the imported rules in the named layer. |
layer |
Wrap them in an anonymous layer. |
supports(...) |
Condition, like in @supports, without the at-rule. |
screen and (...) |
A media query list that controls whether the sheet applies. |
Usage notes
- Performance. A browser discovers an imported sheet only after downloading and parsing the parent, so chains of imports load one after another. In production, prefer several
<link>elements (they download in parallel) or bundle the files. - Imports must be first. Any style rule above an
@importmakes it invalid and ignored. - Layers make imports predictable.
@import url(reset.css) layer(reset);guarantees a reset will lose against your own unlayered rules. - Media in the import still downloads the file in many cases; it only controls whether the rules apply.
- Inside
<style>elements@importworks the same way, but a sheet with a failing import still applies its other rules. - Preprocessors like Sass have their own
@import/@use, which merge files at build time and are not the same as the CSS rule. - Cross-origin imports work for loading styles, but you cannot read their rules from JavaScript.
Browser support
Supported in every browser. The layer() and supports() extensions are Baseline since 2022 and 2023 respectively in current browsers.
Related
@layer@media@charset- Lesson: Adding CSS
- Lesson: Cascade Layers