Importing a CSS file using @import
By Flavio Copes
Learn how to import one CSS file into another with the @import directive, why it must come before any other rules, and how to load files per media like print.
From any CSS file you can import another CSS file using the @import directive. The browser downloads that file and applies its rules as if they were written right where the @import line sits.
Here is how you use it:
@import url(reset.css);
You can also pass the file as a string, without url():
@import 'reset.css';
Both forms work the same. The path can be relative, like above, or an absolute URL pointing to another domain.
This is handy when you want to split a large stylesheet into smaller files. A reset.css, a typography.css, a layout.css, all pulled in from one main file.
Where do you put @import?
One important thing you need to know is that @import directives must be put before any other rule in the file (except @charset), or they will be ignored.
This trips people up because there’s no error. You add an @import at the bottom of a file, the styles never show up, and the console stays quiet. If an import seems to do nothing, check its position first. Move it to the top of the file.
Loading a file for a specific media
You can add media descriptors, so the rules in a file only apply on that media:
@import url(global.css) all;
@import url(screen.css) screen;
@import url(print.css) print;
The rules in print.css only apply when the page is printed. This keeps your print styles in their own file instead of scattering @media print blocks everywhere.
Watch out for performance
Be careful with @import in production. The browser can’t discover the imported file until it has downloaded and parsed the file that imports it. The downloads happen one after the other, not in parallel.
Two <link> tags in your HTML, instead, download at the same time. So a chain of imports can slow down how fast your styles arrive.
Most build tools solve this for you. They resolve @import at build time and merge everything into a single file. You keep the organization benefits while shipping one request.
Related posts about css: