CSS Hack 原理与应用

利用浏览器解析差异实现针对性样式

问题

什么是 CSS Hack?常用的 CSS Hack 有哪些?

解答

CSS Hack 是利用不同浏览器对 CSS 解析的差异,针对特定浏览器编写特定样式的技术。

1. 属性前缀 Hack

.element {
  color: red;       /* 所有浏览器 */
  color: red\9;     /* IE6-IE10 */
  *color: red;      /* IE6-IE7 */
  _color: red;      /* IE6 */
  +color: red;      /* IE6-IE7 */
}

2. 选择器 Hack

/* IE6 及以下 */
* html .element {
  color: red;
}

/* IE7 及以下 */
*+ html .element {
  color: red;
}

/* IE7 */
*:first-child + html .element {
  color: red;
}

3. IE 条件注释

<!-- 仅 IE 可见 -->
<!--[if IE]>
  <link rel="stylesheet" href="ie.css">
<![endif]-->

<!-- IE6 及以下 -->
<!--[if lte IE 6]>
  <link rel="stylesheet" href="ie6.css">
<![endif]-->

<!-- 非 IE 可见 -->
<!--[if !IE]><!-->
  <link rel="stylesheet" href="modern.css">
<!--<![endif]-->

4. @supports 特性查询(现代方案)

/* 支持 Grid 的浏览器 */
@supports (display: grid) {
  .container {
    display: grid;
  }
}

/* 不支持 Grid 的浏览器 */
@supports not (display: grid) {
  .container {
    display: flex;
  }
}

5. 实际应用示例

.clearfix {
  *zoom: 1;  /* IE6-IE7 触发 hasLayout */
}

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

/* 透明度兼容写法 */
.transparent {
  opacity: 0.5;           /* 现代浏览器 */
  filter: alpha(opacity=50); /* IE8 及以下 */
}

关键点

  • CSS Hack 利用浏览器对 CSS 语法解析的差异实现针对性样式
  • 属性前缀 Hack:\9*_ 等符号针对不同 IE 版本
  • 选择器 Hack:* html*+ html 等选择器只被特定浏览器识别
  • 条件注释是 IE 专有的 HTML 注释语法,IE10+ 已不支持
  • 现代开发推荐使用 @supports 特性查询替代传统 Hack