頁面滾動時,某個 DIV 始終固定在視口指定位置 (如頂部、居中),不隨內容滾動。
.fixed-top {
position: fixed;
top: 0; left: 0; right: 0;
z-index: 1000;
/* 無需 JS,性能最好 */
}
.fixed-center {
position: fixed;
left: 50%; top: 50%;
transform: translate(-50%, -50%);
/* 或已知尺寸用負 margin */
}
✅ 簡單、高性能、GPU 加速、無 JS 依賴
❌ IE6 不支持 (已可忽略)
.sticky-top {
position: sticky;
top: 0;
z-index: 100;
/* 滾動到頂部時固定,否則正常流排版 */
}
✅ 適合導航欄、表頭固定
❌ 祖先元素有 overflow: hidden/auto/scroll 會失效
<div id="floatLayer" style="position: absolute; top: 100px; left: 50%; margin-left: -150px; width: 300px;">固定層</div>
<script>
(function() {
var layer = document.getElementById('floatLayer');
var initialTop = layer.offsetTop; // 初始位置
window.onscroll = function() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 滾動超過初始位置時固定
if (scrollTop > initialTop) {
layer.style.position = 'fixed';
layer.style.top = '0';
} else {
layer.style.position = 'absolute';
layer.style.top = initialTop + 'px';
}
};
})();
</script>
✅ IE6+ 兼容
❌ 滾動事件高頻觸發需節流,可能閃爍
<body style="overflow: hidden;">
<iframe src="content.html" style="width:100%;height:100%;" frameborder="0"></iframe>
<div style="position: absolute; left: 50%; top: 50%; margin: -150px 0 0 -150px; width: 300px; height: 300px;">
居中固定層
</div>
</body>
原理:body 鎖死滾動,iframe 內部滾動,浮層相對 body 絕對定位。
❌ SEO 差、滾動條樣式難控、iframe 通信麻煩,**不推薦新項目使用**。
.fixed-ie6 {
position: absolute;
top: expression(eval(document.documentElement.scrollTop + 100));
left: 50%; margin-left: -150px;
/* expression 在重繪時高頻執行,極其消耗性能,現代項目禁用 */
}
| 方案 | 兼容性 | 性能 | 適用場景 |
|---|---|---|---|
| position: fixed | IE7+ / 所有現代 | ★★★★★ | 彈窗、頂部導航、側邊欄、返回頂部 |
| position: sticky | 現代瀏覽器 (IE 不支持) | ★★★★★ | 表頭固定、滾動吸頂導航、分組標題 |
| JS scroll 監聽 | 全兼容 | ★★☆☆☆ | 極舊環境維護、複雜條件觸發固定 |
| iframe 法 | 全兼容 | ★☆☆☆☆ | 極舊項目維護、不得不兼容 IE6 |
.smart-fixed {
position: sticky;
top: 0;
z-index: 100;
}
/* 不支持 sticky 的降級 (可用 @supports 或 JS 檢測) */
@supports not (position: sticky) {
.smart-fixed {
position: fixed;
top: 0;
}
}
/* 或 JS 檢測 */
if (CSS.supports('position', 'sticky') === false) {
// 應用 fixed 方案或 JS 方案
}
fixed 相對最近的 transform/filter/perspective 祖先定位,而非 viewport → 移出這類容器或改用 stickysticky 失效 → 檢查祖先 overflow !== visiblez-index、檢查父元素 z-index 創建新層疊上下文fixed 底部輸入框被鍵盤頂起 → 用 position: sticky; bottom: 0 或視口單位 vh