「固定在螢幕右下角」是很常見的需求:返回頂部按鈕、客服入口、訊息提示框都屬於這一類。關鍵在於 position: fixed——它讓元素以瀏覽器視窗為基準定位,捲動頁面時位置完全不變。
<!DOCTYPE html>
<html>
<head>
<title>CSS position:fixed 實現html元素固定於某位置</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
body {
height: 1000px;
}
#footer {
position: fixed;
background: #eee;
bottom: 20px;
right: 10px;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="footer"></div>
</body>
</html>
body 特意設為 1000px 高,是為了製造出可捲動的頁面,方便驗證效果——如果頁面太短根本不會出現 scrollbar,就無法看出 fixed 與 absolute 的差別。
bottom: 20px; right: 10px; 讓方塊與視窗右下緣保持固定間距,避免貼死邊緣。
以上程式碼已能滿足需求:無論是否捲動頁面,方塊都穩定停留在右下角。