Wabow Information Inc. Blog
分類: 技術分享 作者: jaceju
6 六月 2009本文轉載自[CSS] IE6 模擬 position:fixed 純 CSS 解法
我們都知道 IE6 不支援 position:fixed 。
但 position:fixed 真的很好用,像是廣告、選單這些頁面上常見常用的元素,需要固定在頁面上某個位置時,都可以用 position:fixed 來處理。
所以有很多網路上的先進想出了很多方法來解決 IE6 不支援 position:fixed 的問題,而大部份的解法都是採用 JavaScript 。可惜這些解法除了要擔心瀏覽器關閉 JavaScript 外,通常在移動時都會有抖動的跡象。

所以我就想找找看網路上有沒有純 CSS 解法,沒想到就找到了這篇: Fixing position:fixed for Windows Internet Explorer 。
直接來看範例:
fixed.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Position:fixed on pure css</title> <link href="fixed.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrapper"> <p>TEST LINE </p> <p>TEST LINE</p> <p>TEST LINE</p> <p>TEST LINE</p> ... <p>TEST LINE</p> <p>TEST LINE</p> <p>TEST LINE</p> </div> <div id="fixed"> <ul> <li>ITEM 1</li> <li>ITEM 2</li> <li>ITEM 3</li> <li>ITEM 4</li> <li>ITEM 5</li> </ul> </div> </body> </html>
首先我們先把要捲動的部份用 div#wrapper 包起來,要固定的部份 (div#fixed) 則排除在 div#wrapper 之外;然後先對有支援 position:fixed 的瀏覽器做處理,也就是直接利用 position:fixed 來將 div#fixed 定位。

再來是 CSS 的部份:
html, body{ margin:0; padding:0; } #fixed { position:fixed; width:380px; top:0px; right:100px; }
接下來我們再針對 IE6 做處理,也就是用 * html 這個 hack :
* html { overflow: hidden; } * html body, * html #wrapper { height:100%; overflow:auto; } * html #fixed { position:absolute; }
這裡的原理很簡單,就是將 div#wrapper 的高度設為與 body 同高, overflow 設為 auto 即可。
註:上面那篇參考文章裡只提到 body 要設為高度 100% 和 overflow 為 auto ,但我實驗的結果是連 div#wrapper 也要設成一樣,才會正常動作。
最後把固定的部份用 position:absolute 定住,這樣就完成讓 IE6 模擬 position:fixed 的效果啦~