I have a large CSS file, and I would like to include other CSS files for special cases using media queries.
Is it safe to use @import
in CSS like this:
@media only screen and (max-width: 480px) {
@import url('/css/styles-480.css');
}
I have a large CSS file, and I would like to include other CSS files for special cases using media queries.
Is it safe to use @import
in CSS like this:
@media only screen and (max-width: 480px) {
@import url('/css/styles-480.css');
}
It's not valid to have an @import
within a @media
rule, so what you have won't work.
The correct way to do this is even simpler — @import
itself accepts a media query after the URL:
@import url('/css/styles-480.css') only screen and (max-width: 480px);
This syntax is introduced in CSS2.1 for use with media types, but media queries will also work since they're a direct extension from media types.
Remember that @import
rules can only exist at the beginning of a stylesheet.
If you're concerned about load performance, you may want to use a separate <link>
element in your page head to refer to this stylesheet instead of an @import
, as shown by Asad. However, either way will work just fine.
Instead of importing within a CSS file, I would recommend that you download the CSS file in parallel if it is required:
<link media="only screen and (max-width: 480px)"
href="/css/styles-480.css" type="text/css" rel="stylesheet" />
The problem with using @import
is that the second file is only downloaded after the CSS file containing @import
is completely downloaded and parsed. Regardless of whether you are overriding all your rules or some of your rules, this approach is faster, since it doesn't load the files sequentially.