萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 實現背景圖片固定在容器底部顯示

讓 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 在移動端可能有性能/表現問題,謹慎使用
  • 多背景圖片時,每層屬性用逗號分隔,順序對應疊加順序(第一層最上)
copyright © 萬盛學電腦網 all rights reserved