【问题标题】:CSS import or <link rel...> with "media" attributeCSS 导入或 <link rel...> 带有“媒体”属性
【发布时间】:2011-01-26 03:59:46
【问题描述】:

在页面中包含 CSS 的最佳方法是什么?为什么?

例如:

<style type="text/css">
  @import "style.css" screen, tv;
  @import "print.css" print;
  @import "iphone.css" iphone;
</style>

<LINK rel="stylesheet" media="screen" href="style.css" type="text/css" />
<LINK rel="stylesheet" media="print" href="print.css" type="text/css" />
<LINK rel="stylesheet" media="iphone" href="iphone.css" type="text/css" />

据我所知@import 在古老的浏览器中不起作用,这可能是一个优势,因为这些浏览器只会显示文本而不是不可读的 CSS 混乱(使用链接时)。

【问题讨论】:

  • &lt;link rel="stylesheet" type="text/css" media="screen" href="style.css" /&gt;
  • 但是为什么呢? @import 有什么问题?
  • 我现在太累了,无法写出应得的冗长详细答案,所以我只留下了一条评论,我相当确定这是正确的“答案”。幸运的是,我不必写答案:见here :)
  • 我想出了一个理由来使用@import 作为黑客,也许每两年一次,并且随着旧/IE 的使用而减少。对于包含大量 CSS 的相当大/复杂的网站,@import 可以轻松帮助您更好地组织。

标签: html css stylesheet


【解决方案1】:

已经讨论过很多次了,你可以在这里阅读更多:

http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

Difference between @import and link in CSS

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

提到一些......

就性能影响而言,我个人从不使用@import。

【讨论】:

  • 在第一个链接中作者说Looking at Figure 6, the longest bar is the four second script. Even though it was listed last, it gets downloaded first in IE. If the script contains code that depends on the styles applied from the stylesheets (a la getElementsByClassName, etc.), then unexpected results may occur because the script is loaded before the stylesheets, despite the developer listing it last. ...对不起,但这听起来很荒谬。无论下载顺序如何,浏览器都不能忽略开发者设置的顺序。没有办法像那样应用样式
  • 不幸的是,IE 可以让 Web 开发人员更感兴趣的事情没有尽头。请参阅这篇文章 (developer.yahoo.com/performance/rules.html#csslink),其中指出“在 IE 中 @import 的行为与在页面底部使用 的行为相同,因此最好不要使用它。”这就是为什么许多网站建议在页面上最后加载脚本以及为什么只在 DOM 准备好之后才运行 JS 是一种好的做法。
【解决方案2】:

实际上两者都实现了相同的目标,但存在一些细微差别。即:

  1. @import 在 IE6 及更早版本和 Netscape 4 中不受支持
  2. @import 允许在单个链接或样式元素中导入多个样式表(如果需要)
  3. 链接允许指定备用样式表,FireFox、Safari 和 Opera 等浏览器可以允许用户切换到该样式表。如果使用 JavaScript 切换器,IE 也支持这一点。这最常用于可访问性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2016-06-20
    相关资源
    最近更新 更多