Best way to include CSS? Why use @import?

Go To StackoverFlow.com

251

Basically I am wondering what is the advantage / purpose of using @import to import stylesheets into an existing stylesheet versus just adding another ...

<link rel="stylesheet" type="text/css" href="" />

to the head of the document?

2012-04-05 22:37
by NoName
Portability is the first one that comes to mind. If you want to include a set of CSS files in various pages, its easier and more maintainable to have to link just one CSS file in each page, rather than 5 - xbonez 2012-04-05 22:40
@xbonez: In most such situations, though, there will be a significant amount of other common HTML involved, so it's generally better to just link both stylesheets in a template - duskwuff 2012-04-05 22:49
back in the bad old days, @import was handy to support both "good" browser (Netscape 4, IE5) and bad browser (IE3, N3). Nowadays, it's nearly useless - mddw 2012-04-05 22:51
http://www.stevesouders.com/blog/2009/04/09/dont-use-import - chharvey 2015-10-13 15:25
is a void element in HTML5, so.. you can use it without the slash, like, <link rel="stylesheet" type="text/css" href="theme.css"> - Константин Ван 2016-02-14 15:58
If my mind don't lying, @import is a good thing when you have troubles with url() at CSS. Example: background:url(images/img.jpg) in css/style.css will search image at css/images/img.jpg, while @import must do it right way - Arman Hayots 2016-03-03 08:28


303

From a page speed standpoint, @import from a CSS file should almost never be used, as it can prevent stylesheets from being downloaded concurrently. For instance, if stylesheet A contains the text:

@import url("stylesheetB.css");

then the download of the second stylesheet may not start until the first stylesheet has been downloaded. If, on the other hand, both stylesheets are referenced in <link> elements in the main HTML page, both can be downloaded at the same time. If both stylesheets are always loaded together, it can also be helpful to simply combine them into a single file.

There are occasionally situations where @import is appropriate, but they are generally the exception, not the rule.

2012-04-05 22:47
by duskwuff
There are occasionally situations where @import is appropriate Like using @media to apply different styles to different devices - XXX 2012-04-05 22:53
Thanks guys... All answers are very helpful. I am not really sure which one to pick as they all seem to have valid points - NoName 2012-04-05 22:56
Another reason would be to add an @import for a Google font into the style sheet (e.g. @import url(http://fonts.googleapis.com/css?family=Archivo+Narrow);), so that you don't have to paste a link into every page using that stylesheet - cayhorstmann 2013-01-17 05:40
Yes, that would be one of the exceptions I mentioned. : - duskwuff 2013-01-17 05:41
For those who are curious: one of my favorite uses of @import is when you have a build process set up using something like <code>grunt-concat-css</code>. During development, the @import statements work and page load speed isn't a concern. Then, when you're building for production, a tool like this will concatenate all of your CSS files appropriately and remove the @import. I do a similar thing with my JavaScript files using <code>grunt-browserify</code> - Brandon 2013-12-03 00:05
@Brandon is that possible on a shared virtual private server running a WAMP stack - Ben Leggiero 2015-04-20 14:27
@Ben It depends on how you're deploying, I suppose. I used the grunt tools I mentioned as part of my build process. That is, the CSS is concatenated (and minified for that matter) on my machine before it is deployed to the server. So, once it's on the server, it's just a static CSS file like any other and should thus be agnostic to the server environment. If you're talking about having the build process run remotely on the server, I can't really speak for support of node.js, grunt, etc. in such an environment - Brandon 2015-04-20 19:36
@Brandon alright, thanks! Currently, I'm using PHP regex replace of comments with '' and whitespace (incl. newlines) with ' ' - Ben Leggiero 2015-04-20 19:42
@Derek朕會功夫 If you are using @import to apply device specific styles, why not just use a <link> tag with a media attribute - Jomar Sevillejo 2016-06-10 03:28
in my experience @import url("stylesheetB.css"); is more faster,i tried both and import url("stylesheetB.css") but import url("stylesheetB.css"); is much faste - NoName 2017-02-19 09:53
@MuhammedAsif There is no reason why @import would be faster. You're probably looking at some sort of measurement artifact - duskwuff 2017-02-19 18:31
is this still the case?? @MuhammedAsif do you have any data or tests to back that up? - Anthony 2017-10-07 14:03
yes, i'm still using the same - NoName 2017-10-08 15:57


159

I'm going to play devil's advocate, because I hate it when people agree too much.

1. If you need a stylesheet that depends on another one, use @import. Do the optimization in a separate step.

There are two variables you're optimizing for at any given time - the performance of your code, and the performance of the developer. In many, if not a majority of cases, it's more important to make the developer more efficient, and only then make the code more performant.

If you have one stylesheet that depends on another, the most logical thing to do is to put them in two separate files and use @import. That will make the most logical sense to the next person who looks at the code.

(When would such a dependency happen? It's pretty rare, in my opinion - usually one stylesheet is enough. However, there are some logical places to put things in different CSS files:)

  • Theming: If you have different color schemes or themes for the same page, they may share some, but not all components.
  • Subcomponents: A contrived example - say you have a restaurant page that includes a menu. If the menu is very different from the rest of the page, it'll be easier to maintain if it's in its own file.

Usually stylesheets are independent, so it's reasonable to include them all using <link href>. However, if they are a dependent hierarchy, you should do the thing that makes the most logical sense to do.

Python uses import; C uses include; JavaScript has require. CSS has import; when you need it, use it!

2. Once you get to the point where the site needs to scale, concatenate all the CSS.

Multiple CSS requests of any kind - whether through links or through @imports - are bad practice for high performance web sites. Once you're at the point where optimization matters, all your CSS should be flowing through a minifier. Cssmin combines import statements; as @Brandon points out, grunt has multiple options for doing so as well. (See also this question).

Once you're at the minified stage, <link> is faster, as people have pointed out, so at most link to a few stylesheets and don't @import any if at all possible.

Before the site reaches production scale though, it's more important that the code is organized and logical, than that it goes slightly faster.

2014-04-19 21:28
by Chris
+1 for playing the 'bad guy' while making really would points that contribute to a broader view on the subject - harogaston 2014-07-11 23:43


14

It is best to NOT use @import to include CSS in a page for speed reasons. See this excellent article to learn why not: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

Also it is often harder to minify and combine css files that are served via the @import tag, because minify scripts cannot "peel out" the @import lines from other css files. When you include them as <link tags you can use existing minify php/dotnet/java modules to do the minification.

So: use <link /> instead of @import.

2012-04-05 22:50
by Koen Peters
If you are using grunt for instance you can also take advantage of the @import by using combine. Then the imported stylesheet is embedded making it one. Which for me is to get the best of both worlds - bjorsig 2016-11-15 16:21


11

using the link method, the stylesheets are loaded parallel (faster and better), and nearly all browsers support link

import loads any extra css files one-by-one (slower), and could give you Flash Of Unstyled Content

2012-04-05 22:51
by mowgli


8

@Nebo Iznad Mišo Grgur

The following are all correct ways to use @import

@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;
@import 'custom.css';
@import url("chrome://communicator/skin/");
@import "common.css" screen, projection;
@import url('landscape.css') screen and (orientation:landscape);

source: https://developer.mozilla.org/en-US/docs/Web/CSS/@import

2013-10-31 14:12
by BBagi


6

There is not really much difference in adding a css stylesheet in the head versus using the import functionality. Using @import is generally used for chaining stylesheets so that one can be easily extended. It could be used to easily swap different color layouts for example in conjunction with some general css definitions. I would say the main advantage / purpose is extensibility.

I agree with xbonez comment as well in that portability and maintainability are added benefits.

2012-04-05 22:45
by Travis J


3

They are very similar. Some may argue that @import is more maintainable. However, each @import will cost you a new HTTP request in the same fashion as using the "link" method. So in the context of speed it is no faster. And as "duskwuff" said, it doesn't load simultaneously which is a downfall.

2012-04-05 22:54
by Kris Hollenbeck


3

One place where I use @import is when I'm doing two versions of a page, English and French. I'll build out my page in English, using a main.css. When I build out the French version, I'll link to a French stylesheet (main_fr.css). At the top of the French stylesheet, I'll import the main.css, and then redefine specific rules for just the parts I need different in the French version.

2013-10-31 14:09
by BBagi


3

Quoted from http://webdesign.about.com/od/beginningcss/f/css_import_link.htm

The main purpose of @import method is to use multiple style sheets on a page, but only one link in your < head >. For example, a corporation might have a global style sheet for every page on the site, with sub-sections having additional styles that only apply to that sub-section. By linking to the sub-section style sheet and importing the global styles at the top of that style sheet, you don't have to maintain a gigantic style sheet with all the styles for the site and every sub-section. The only requirement is that any @import rules need to come before the rest of your style rules. And remember that inheritance can still be a problem.

2014-04-19 22:05
by Vishnuraj V


3

Sometimes you have to use @import as opposed to inline . If you are working on a complex application that has 32 or more css files and you must support IE9 there is no choice. IE9 ignores any css file after the first 31 and this includes and inline css. However, each sheet can import 31 others.

2015-08-04 22:55
by Carl


3

There are many GOOD reasons to use @import.

One powerful reason for using @import is to do cross-browser design. Imported sheets, in general, are hidden from many older browsers, which allows you to apply specific formatting for very old browsers like Netscape 4 or older series, Internet Explorer 5.2 for Mac, Opera 6 and older, and IE 3 and 4 for PC.

To do this, in your base.css file you could have the following:

@import 'newerbrowsers.css';

body {
  font-size:13px;
}

In your imported custom sheet (newerbrowsers.css) simply apply the newer cascading style:

html body {
  font-size:1em;
}

Using "em" units is superior to "px" units as it allows both the fonts and design to stretch based on user settings, where as older browsers do better with pixel-based (which are rigid and cannot be changed in browser user settings). The imported sheet would not be seen by most older browsers.

You may so, who cares! Try going to some larger antiquated government or corporate systems and you will still see those older browsers used. But its really just good design, because the browser you love today will also someday be antiquated and outdated as well. And using CSS in a limited way means you now have an even larger and growing group of user-agents that dont work well with you site.

Using @import your cross-browser web site compatibility will now reach 99.9% saturation simply because so many older browser wont read the imported sheets. It guarantees you apply a basic simple font set for their html, but more advanced CSS is used by newer agents. This allows content to be accessible for older agents without compromising rich visual displays needed in newer desktop browsers.

Remember, modern browsers cache HTML structures and CSS extremely well after the first call to a web site. Multiple calls to the server is not the bottleneck it once was.

Megabytes and megabytes of Javascript API's and JSON uploaded to smart devices and poorly designed HTML markup that is not consistent between pages is the main driver of slow rendering today. Youre average Google news page is over 6 megabytes of ECMAScript just to render a tiny bit of text! LOL

A few kilobytes of cached CSS and consistent clean HTML with smaller javascript footprints will render in a user-agent in lightning speed simply because the browser caches both consistent DOM markup and CSS, unless you choose to manipulate and change that via javascript circus tricks.

2017-07-18 00:07
by Stokely


2

I think the key in this are the two reasons why you are actually writing multiple CSS style sheets.

  1. You write multiple sheets because the different pages of your website require different CSS definitions. Or at least not all of them require all the CSS definitions one other pages require. So you split up the CSS files in order to optimize what sheets are load on the different pages and avoid loading too many CSS definitions.
  2. The second reason that comes to mind is that your CSS is getting that large that is becomes clumsy to handle and in order to make it easier to maintain the large CSS file you split them up into multiple CSS files.

For the first reason the additional <link> tag would apply as this allows you to load different set of CSS files for different pages.

For the second reason the @import statement appears as the most handy because you get multiple CSS files but the files loaded are always the same.

From the perspective of the loading time there is no different. The browser has to check and download the seperated CSS files no matter how they are implemented.

2012-04-05 22:47
by Nitram
You say "From the perspective of the loading time there is no different. The browser has to check and download the seperated CSS files no matter how they are implemented." This isn't correct though. the browser can download several CSS files in parallel, but for @ import CSS files, they have to be downloaded, parsed and then the @ import files downloaded. This will slow your page load speed down, especially if the imported CSS file has it's own @ import file - cyberspy 2015-05-21 13:29


2

Use @import in your CSS if you are using a CSS RESET, like Eric Meyer's Reset CSS v2.0, so it does it's job before applying your CSS, thus preventing conflicts.

2013-12-17 17:34
by user2847941


2

I think @import is most useful when writing code for multiple devices. Include a conditional statement to only include the style for the device in question, then only one sheet gets loaded. You can still use the link tag to add any common style elements.

2014-09-27 17:27
by Ethan


0

I experienced a "high peak" of linked stylesheets you can add. While adding any number of linked Javascript wasn't a problem for my free host provider, after doubling number of external stylesheets I got a crash/slow down. And the right code example is:

@import 'stylesheetB.css';

So, I find it useful for having a good mental map, as Nitram mentioned, while still at hard-coding the design. Godspeed. And I pardon for English grammatical mistakes, if any.

2013-09-10 22:46
by mggluscevic


-2

There is almost no reason to use @import as it loads every single imported CSS file separately and can slow your site down significantly. If you are interested in the optimal way to deal with CSS(when it comes to page speed), this is how you should deal with all your CSS code:

  • Open all your CSS files and copy the code of every single file
  • Paste all the code in between a single STYLE tag in the HTML header of your page
  • Never use CSS @import or separate CSS files to deliver CSS unless you have a large amount of code or there is a specific need to.

More detailed information here: http://www.giftofspeed.com/optimize-css-delivery/

The reason the above works best is because it creates less requests for the browser to deal with and it can immediately start rendering the CSS instead of downloading separate files.

2014-11-12 15:37
by William Dresker
An extremely narrow, but valid, view of the term "optimization". For your sanity, use a tool during the publication phase to achieve this kind of optimization. Until then do whatever helps you think and code faster - Jesse Chisholm 2014-12-03 17:21
Since most websites have more than 1 page, and each one generally uses the same css, wouldn't it be faster to use a css file (linked in the header)? This will cause it to be transferred once, then used form the browser cache (often in memory), versus the downloading of the whole thing for every page when it is part of the html of every page - Legolas 2015-05-07 09:49
it's a disaster to copy all CSS files and paste inside STYLE.. Better to include at least 1 css in <HEAD>T.Todua 2015-06-17 12:40
This completely ignores browser cachin - Michiel 2015-11-30 13:10
I am assuming this answer is a joke? (the gratuitous bold type, and the linked page says not to use style tags - Sanjay Manohar 2017-07-25 11:21


-2

This might help a PHP developer out. The below functions will strip white space, remove comments, and concatenate of all your CSS files. Then insert it into a <style> tag in the head before page load.

The function below will strip comments and minify the passed in css. It is paired in conjunction with the next function.

<?php
function minifyCSS($string)
{
    // Minify CSS and strip comments

    # Strips Comments
    $string = preg_replace('!/\*.*?\*/!s','', $string);
    $string = preg_replace('/\n\s*\n/',"\n", $string);

    # Minifies
    $string = preg_replace('/[\n\r \t]/',' ', $string);
    $string = preg_replace('/ +/',' ', $string);
    $string = preg_replace('/ ?([,:;{}]) ?/','$1',$string);

    # Remove semicolon
    $string = preg_replace('/;}/','}',$string);

    # Return Minified CSS
    return $string;
}
?>

You will call this function in the head of your document.

<?php
function concatenateCSS($cssFiles)
{
    // Load all relevant css files

    # concatenate all relevant css files
    $css = '';
    foreach ($cssFiles as $cssFile)
    {
        $css = $css . file_get_contents("$cssFile.css");
    }

    # minify all css
    $css = minifyCSS($css);
    echo "<style>$css</style>";
}
?>

Include the function concatenateCSS() in your document head. Pass in an array with the names of your stylesheets with its path IE: css/styles.css. You are not required to add the extension .css as it is added automatically in the function above.

<head>
    <title></title>
    <?php
    $stylesheets = array(
        "bootstrap/css/bootstrap.min", 
        "css/owl-carousel.min", 
        "css/style"
        );
    concatenateCSS( $stylesheets );
    ?>
</head>
2016-03-29 22:18
by Adam Joseph Looze
I think it would be a lot better to just 'minify' the contents of your CSS manually then looping through chosen style sheets and adding them all to every page. Also file_get_contents() is considerably slower than using cURL - Connor Simpson 2016-09-16 20:14
This is a bad idea which prevents the browser cache from being utilized - reformed 2017-12-08 22:40
Ads