Search code examples
cssmedia-queries

Is it possible to include a CSS file into another CSS file with a media query?


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');    
}

Solution

  • 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.