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');
}
Yes, It is possible to include one CSS file in another and it can be done multiple times. Also, import multiple CSS files in the main HTML file or in the main CSS file. It can be done by using @import keyword. portal. It is an educational website. Prepare for the preparation course. <!-- Including one css file into other -->
Aggregate CSS into one file to avoid multiple HTTP requests. That is, copy the contents of base.css and special.css into base-special.css and reference only base-special.css). Importing CSS file into another CSS file is possible. It must be the first rule in the style sheet using the @import rule.
If you want to divide your CSS between various files use Less. In Less the import statement happens on the server and the output is cached and does not create a performance penalty by forcing the client to make another connection. Sass is also an option another not one I have explored.
url|string: A url or a string represents the location of the resource to be imported. The url may be relative or absolute. list-of-mediaqueries: The list of media queries condition the application of the CSS rules defined in the linked URL.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With