position: fixed 能讓元素固定在視窗的頂端或底端,但舊版 IE 不支援。若需要兼容 IE6、IE7 與 Firefox,通常要搭配 expression 或條件註解。
在標準瀏覽器中,直接使用 position: fixed。在 IE6 中,則用 expression 計算捲動後的位置,讓元素模擬固定效果。為了避免捲動時閃動,可將 body 背景設為 fixed。
body {
background-image: url(about:blank);
background-attachment: fixed;
}
.head, .foot {
position: fixed !important;
position: absolute;
z-index: 21;
background: #999;
height: 30px;
width: 500px;
}
.foot {
bottom: 0 !important;
}
.main {
height: 2000px;
}
若只針對 IE6,可在條件註解中為頂部與底部元素加上 top: expression(...),依捲動值即時修正位置。這種做法效能較差,且只適合維護舊專案。
現代開發中,若目標瀏覽器已不支援舊版 IE,直接使用 fixed 即可;若仍有多版本需求,則應把 expression 限制在必要的條件區塊中,避免影響主要樣式。