我們都知道 IE6 不支援 position:fixed 。
但 position:fixed 真的很好用,像是廣告、選單這些頁面上常見常用的元素,需要固定在頁面上某個位置時,都可以用 position:fixed 來處理。
所以有很多網路上的先進想出了很多方法來解決 IE6 不支援 position:fixed 的問題,而大部份的解法都是採用 JavaScript 。可惜這些解法除了要擔心瀏覽器關閉 JavaScript 外,通常在移動時都會有抖動的跡象。

所以我就想找找看網路上有沒有純 CSS 解法,沒想到就找到了這篇: Fixing position:fixed for Windows Internet Explorer 。
直接來看範例:
fixed.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| <!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 的部份:
1
2
3
4
5
6
7
8
9
10
| html, body{
margin:0;
padding:0;
}
#fixed {
position:fixed;
width:380px;
top:0px;
right:100px;
}
|
接下來我們再針對 IE6 做處理,也就是用 * html 這個 hack :
1
2
3
4
5
6
7
8
9
10
11
12
13
| * html {
overflow: hidden;
}
* html body,
* html #wrapper {
position:relative;
width:100%;
height:100%;
overflow:auto;
}
* html #fixed {
position:absolute;
}
|
這裡的原理很簡單,就是將 div#wrapper 的高度設為與 body 同高, overflow 設為 auto 即可。
註:上面那篇參考文章裡只提到 body 要設為高度 100% 和 overflow 為 auto ,但我實驗的結果是連 div#wrapper 也要設成一樣,才會正常動作。
最後把固定的部份用 position:absolute 定住,這樣就完成讓 IE6 模擬 position:fixed 的效果啦~