基本上,我想知道使用@import将样式表导入到现有的样式表中,而不是仅仅添加另一个样式表的优势/目的是什么…

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

文件的开头?


当前回答

我使用@import的一个地方是当我处理一个页面的两个版本时,英语和法语。我将使用main.css用英文构建我的页面。在构建法语版本时,我将链接到一个法语样式表(main_fr.css)。在法语样式表的顶部,我将导入main.css,然后为法语版本中需要不同的部分重新定义特定的规则。

其他回答

从页面速度的角度来看,几乎不应该使用CSS文件中的@import,因为它会阻止样式表被并发下载。例如,如果样式表A包含以下文本:

@import url("stylesheetB.css");

然后,第二个样式表的下载可能要等到第一个样式表下载完成后才开始。另一方面,如果在主HTML页面的<link>元素中引用了这两个样式表,则可以同时下载这两个样式表。如果两个样式表总是一起加载,那么将它们合并到一个文件中也会很有帮助。

有时@import是合适的,但它们通常是例外,而不是规则。

我认为这里的关键是你为什么要编写多个CSS样式表的两个原因。

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

第一个原因是附加的<link>标记将应用,因为这允许您为不同的页面加载不同的CSS文件集。

对于第二个原因,@import语句似乎是最方便的,因为您可以获得多个CSS文件,但加载的文件总是相同的。

从装载时间的角度来看并没有什么不同。浏览器必须检查和下载分离的CSS文件,无论它们是如何实现的。

@Nebo在伊兹纳德米索格古尔

下面是使用@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);

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

如果你使用的是CSS RESET,比如Eric Meyer的RESET CSS v2.0,在你的CSS中使用@import,这样它就能在应用你的CSS之前完成它的工作,从而防止冲突。

它们非常相似。有些人可能认为@import更易于维护。但是,每个@import都将花费您一个新的HTTP请求,其方式与使用“link”方法相同。所以在速度的背景下,它并不更快。正如“duskwuff”所说,它不能同时加载,这是一个缺点。