網路上關於「如何把廣告固定定位在瀏覽器右下角」的解法多不勝數,大部分都要動用 JavaScript 去計算捲軸位置。其實光靠樣式表就能完成,而且程式碼短得多。
在 IE7 與 Firefox 這類現代瀏覽器中,position: fixed 就能把圖層釘在視窗的任意位置。元素會脫離文件流程,相對視窗而非文件定位,捲動時不動如山——這正是我們要的行為。
真正麻煩的是 IE6:它完全不認 position: fixed。以下程式碼主要是寫給它的。
body { margin: 0; border: 0; height: 100%; overflow-y: auto; }
#test { display: block; bottom: 3px; right: 3px; width: 130px; position: fixed; }
/* 以下是寫給 IE6 的 */
* html #test { position: absolute; right: 18px; }
* html { overflow-x: auto; overflow-y: hidden; }
* html 是一個只有 IE6 能識別的選擇器寫法(因為 IE6 有一個神祕的、不存在的 html 元素作為祖先),用來把樣式單獨餵給它。
關鍵技巧在於:讓 body 自己成為捲動容器(height:100%; overflow-y:auto),捲軸就不再屬於 html 元素。當捲動的責任從 html 轉移到 body,position: absolute 的定位基準就跟著改變,圖層便能在捲動時保持相對穩定。這是一個利用 IE6 quirks 行為的經典手法。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body { margin:0; border:0; height:100%; overflow-y:auto; }
#test { display:block; bottom:3px; right:3px; position:fixed; }
* html #test { position:absolute; right:18px; }
* html { overflow-x:auto; overflow-y:hidden; }
</style>
<title>Fixed layer in MSIE - position:fixed</title>
</head>
<body>
<div>
<h1>Fixed layer in MSIE</h1>
<p>這是對 IE 的 position:fixed 的模擬。頁面主體放在一個高度 100%、可捲動的 div 中,捲軸屬於該 div 而非 body。</p>
</div>
<div id="test">
<img src="/files/090701/1_080301.jpg" />
</div>
</body>
</html>
這套做法在當年並非萬靈丹。整理下已知狀況:
overflow-y: hidden,會出現兩組捲軸。如果這個需求出現在現在的專案裡,答案單純得多:
.ad {
position: fixed;
right: 12px;
bottom: 12px;
width: 130px;
z-index: 9999;
}
不需要 hack、不需要條件註解、不需要 JS。IE6 已正式退場多年,為它寫 hack 的成本早已超過收益。
唯一仍值得留意的是行動裝置:小型螢幕上固定廣告容易遮擋內容、誤觸率高,多數使用者體驗指南與搜尋引擎政策都對此有規範。實務上建議加上媒體查詢,在窄螢幕下取消固定定位,或至少縮小佔用面積。
@media (max-width: 600px) {
.ad { display: none; }
}