Can I include a CSS file in another CSS file with a media query?

I have a large CSS file and I would like to include other CSS files for special occasions using media queries.

Is it possible to use @import in CSS like this:

 @media only screen and (max-width: 480px) { @import url('/css/styles-480.css'); } 
+6
source share
2 answers

Instead of importing into a CSS file, I would recommend that you load the CSS file in parallel if necessary:

 <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 loaded after the CSS file containing @import is fully loaded and parsed. Regardless of whether you redefine all of your rules or some of your rules, this approach is faster because it does not load files sequentially.

+3
source

It is not @import have @import inside the @media , so what you have will not work.

The right way to do this is even easier - @import itself accepts the media request after the URL:

 @import url('/css/styles-480.css') only screen and (max-width: 480px); 

This syntax is presented in CSS2.1 for use with media types , but will also work as they are a direct extension of media types.

Remember that @import rules can only exist at the beginning of a stylesheet.

If you are concerned about loading, you can use the separate <link> element in the page title to refer to this stylesheet instead of @import , as shown by Assad . However, any method will work fine.

+14
source

All Articles