讓 div 背景圖片固定顯示在容器底部,是常見的視覺設計需求。通過 background-position 精準控制定位,配合其他背景屬性實現多樣效果。
.bottom-bg {
background-image: url('/images/bg.jpg');
background-repeat: no-repeat;
background-position: center bottom; /* 關鍵:水平居中、垂直底部 */
/* 簡寫寫法 */
background: url('/images/bg.jpg') no-repeat center bottom;
}
| 屬性 | 值 | 效果 |
|---|---|---|
background-position-x |
left / center / right / 長度值 / 百分比 |
水平位置:左/中/右/具體偏移 |
background-position-y |
top / center / bottom / 長度值 / 百分比 |
垂直位置:上/中/下/具體偏移 |
background-repeat |
no-repeat / repeat / repeat-x / repeat-y |
不重複 / 全平鋪 / 僅水平 / 僅垂直 |
background-attachment |
scroll / fixed / local |
隨內容滾動 / 固定視口 / 隨元素滾動 |
body {
background: url('/images/footer-bar.png') no-repeat center bottom fixed;
padding-bottom: 80px; /* 預留空間避免內容被遮擋 */
}
.card {
position: relative;
padding-bottom: 60px; /* 預留水印空間 */
}
.card::after {
content: "";
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
width: 100px;
height: 40px;
background: url('/images/watermark.png') no-repeat center center;
opacity: 0.3;
pointer-events: none;
}
.input-with-icon {
background: url('/images/search-icon.svg') no-repeat right 12px center;
padding-right: 40px; /* 避免文字遮擋圖標 */
}
.responsive-bg {
background: url('/images/banner.jpg') no-repeat;
background-size: cover; /* 覆蓋容器,保持比例 */
background-position: center 80%; /* 重點展示區域偏下 80% */
}
background-position: bottom 等同于 center bottom(水平默認居中)background-attachment: fixed 在移動端可能有性能/表現問題,謹慎使用