IE 7、Firefox、Opera 都支援 CSS 的 {position:fixed},所以「固定定位」本身一行就能搞定。真正麻煩的是 IE 6 及更早版本——以下整理幾種方案與它們的限制。
在 !DOCTYPE 宣告指定 standards-compliant(標準)模式下,可以透過 CSS hack 實現。
原理是:把 html 設為 overflow: hidden、body 設為 height: 100%; overflow: auto,讓捲軸改由 body 負責。此時 body 的內容不會移動,而 position: absolute 的元素相對於 html 定位,視覺上就「固定」住了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
#fixed { position: fixed; top: 5em; right: 0; }
/* 針對 IE7、Opera、Firefox,一行搞定 */
</style>
<!--[if IE 6]>
<style type="text/css">
html { overflow: hidden; }
body { height: 100%; overflow: auto; }
#fixed { position: absolute; right: 17px; }
/* fixed 元素的絕對位置相對於 HTML 元素,而捲軸屬於 body,
這是設 right: 17px 的原因 */
</style>
<![endif]-->
<!--[if lt IE 6]>
<style type="text/css">
#fixed {
position: absolute;
top: expression(eval(document.body.scrollTop + 50));
}
</style>
<![endif]-->
</head>
<body>
<div id="wrapper">……</div>
<div id="fixed"><h2>{position:fixed}</h2></div>
</body>
</html>
在標準模式下,IE 5 與 IE 5.5 目前沒有發現純 CSS 的解法,只能透過 IE 特有的 expression 在 CSS 中嵌入腳本(移動頁面時固定元素會抖動)。原理和常見的「浮動 Logo 廣告」一樣,只是可以直接寫在 CSS 裡,比較簡便。
好消息是利用 IE 獨有的條件註解可以針對不同版本精準下發樣式,同時避免這些代碼被其他瀏覽器讀到——個人認為這比純粹的 CSS Hack 好得多。若你安裝了多個 IE(含綠色版),條件註解會以最高版本為準。
有些人在 !DOCTYPE 宣告(XHTML 1.0 Strict 或 XHTML 1.1)前面喜歡加上 XML Prolog:
<?xml version="1.0" encoding="utf-8"?>
加了這行之後,IE 7 以下都會進入 quirks(相容)模式,上述針對 IE 6 的 Hack 就失效了。這時你得改用 expression 來處理 IE 6。
而在 quirks 模式下,IE 6 對 CSS 的解析方式與 IE 5.5 幾乎雷同,於是找到了一個統一的解法:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"https://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh">
<head>
<!--[if lt IE 7]>
<style type="text/css">
body { overflow: hidden; }
#wrapper { height: 100%; overflow: auto; }
#fixed { position: absolute; right: 17px; }
</style>
<![endif]-->
</head>
<body>
<div id="wrapper">……</div>
<div id="fixed"><h2>{position:fixed}</h2></div>
</body>
</html>
用 if lt IE 7 一條條件註解,就同時覆蓋了 IE 6、5.5、5。
比對兩組純 CSS hack 會發現原理相似,都在於 html 與 body 元素的使用,以及對 position:fixed 的支援程度。但這本質上是一種 Hack,基本上不具通用性,知道方法即可。
要特別注意:
或許有人會想:既然可以引入 XML Prolog、又能用純 CSS 解決 IE7 以下的問題,這下爽了。但加上 XML Prolog 後會發現 IE 6 進入 quirks 模式,原本在標準模式下設計好的版面又變形了——這就是當年做 IE 相容的常態。
今天的結論很輕鬆:IE 6/5 已無支援意義,直接用 position: fixed 即可。唯一需要留意的現代議題是行動裝置:iOS Safari 在舊版本對 fixed 有已知問題,鍵盤彈出時也可能導致元素跳位,實務上仍需在真機上驗證。