We know that there are two ways to reference external CSS in web pages, namely: @import and link. We often hear people say that it is better to use link to introduce CSS, but do you know why?
link ![div css xhtml xml Example Source Code](https://images.downcodes.com/u/info_img/2009-06/09/4504_quote.gif)
Example Source Code
[www.downcodes.com] Link is to connect external CSS to the web page. The specific form is <link href="http://www.downcodes.com/styles.css" type="text/css" />
@import ![div css xhtml xml Example Source Code](https://images.downcodes.com/u/info_img/2009-06/09/4504_quote.gif)
Example Source Code
[www.downcodes.com] The difference between import and link is that it can introduce several other CSS files into one CSS file. The specific form is <style type="text/css">@import url("http://www.downcodes.com/ styles.css");</style>
Why use @import
Most people use @import because old browsers do not support @import, which means we can use @import to introduce CSS styles that only modern browsers can parse.
Use the following code to prevent browsers IE6 and below from parsing the CSS (the methods below IE6 are in disrepair and will be omitted here)
@import url(../style.css) screen;
Another main reason is when your web page needs to introduce several external CSS files. You need to use link to introduce a CSS, and then use @import method to introduce several other CSS files in this CSS file.
Why use link
One of the main reasons for using the link method is that you can allow users to switch CSS styles. Modern browsers such as Firefox, Opera, and Safari all support the rel="alternate stylesheet" attribute (that is, you can choose different styles on the browser). Of course, you You can also use Javascript to enable IE to support users changing styles.
Small problems with @import. If the head tag of your web page is very simple, with only the @import attribute. When the user browses on a slow Internet speed, he will see a page without styles, and then the CSS file will be downloaded. You can see the proper style. To avoid this problem, you need to ensure that there is at least one script or link tag in the head.
Which method should be used? At present, it seems that for small websites, it is more appropriate (or more popular) to use link. Of course, if we need to modularize CSS in the future, we will definitely use @import.
The article is partially translated from What's the Difference Between @import and link for CSS? for learning purposes, welcome to add.