如果你留意過本站右下角那個標著 top 的黑色小三角,會發現無論頁面捲動多遠,它都紋絲不動。這正是 CSS 定位屬性 position: fixed 的效果——讓元素脫離文檔流,固定在瀏覽器的某個位置上。
支援情況大致如下:
基本實作如下:
<style type="text/css">
#fixed { position: fixed; top: 5em; right: 0; }
</style>
<!--[if IE 6]>
<style type="text/css">
html { overflow: hidden; }
body { height: 100%; overflow: auto; }
/* fixed 元素的定位基準是 html,捲動條屬於 body,因此是 17px */
#fixed { position: absolute; right: 17px; }
</style>
<![endif]-->
<!--[if lt IE 6]>
<style type="text/css">
#fixed { position: absolute; top: expression(eval(document.body.scrollTop + 50)); }
</style>
<![endif]-->
IE6 的做法其實很巧妙:讓 html 承擔隱藏溢出的角色,把捲動交給 body,於是相對於 html 絕對定位的元素在視覺上就固定不動了。
另一個容易忽略的細節是 XML Prolog。如果你習慣在 DOCTYPE 前加上 <?xml version="1.0" encoding="utf-8"?>,IE7 以下會被推入 Quirks 模式,此時針對 IE6 的 hack 便失效。Quirks 模式下 IE6 的 CSS 解析方式與 IE5.5 幾乎一致,可以改用統一寫法:
<!--[if lt IE 7]>
<style type="text/css">
body { overflow: hidden; }
#wrapper { height: 100%; overflow: auto; }
#fixed { position: absolute; right: 17px; }
</style>
<![endif]-->
還有一點值得記住:IE6 標準模式下,無論你怎麼設定 html 的寬高,它永遠填滿視窗可視區域;而在 IE5 與 Quirks 模式下,html 與 body 的寬高設定會被完全忽略,同樣保持填滿。理解這層差異,才能判斷 hack 為何有效。
於是就出現一個尷尬局面:加上 XML Prolog 雖然換來 IE7 以下的純 CSS 解法,卻也把 IE6 打進 Quirks,原本在標準模式下正常的設計跟著走樣。這大概就是那個年代做 IE 兼容的宿命。