萬盛學電腦網

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

DIV 底部固定背景圖片:background-position 精準控制與固定/捲動附著實作

核心屬性速查

屬性作用常用值
background-image背景圖片路徑url("path/to/img.jpg")
background-repeat平鋪方式repeat / no-repeat / repeat-x / repeat-y
background-attachment固定/捲動scroll(預設) / fixed / local
background-position定位基準點關鍵字 / 百分比 / 長度 / 組合
background-size縮放大小auto / cover / contain / 長度 / 百分比

底部固定背景:完整代碼

.footer-bg {
  background-image: url("/images/bg-footer.jpg");
  background-repeat: no-repeat;
  background-attachment: fixed;      /* 相對視窗固定,捲動時視差效果 */
  background-position: center bottom; /* 水平置中、垂直靠底 */
  background-size: cover;            /* 覆蓋容器,保持比例 */
  min-height: 300px;                 /* 確保容器有高度顯示背景 */
}

background-position 九宮格關鍵字

left top      | center top      | right top
left center   | center center   | right center
left bottom   | center bottom   | right bottom

單一關鍵字會自動補另一軸為 center:bottom ≡ center bottom。

百分比與長度定位細節

  • 百分比:以「容器尺寸 - 圖片尺寸」為基準。50% 50% 置中,100% 100% 右下角
  • 長度:以容器左上角 (0,0) 為原點。20px 30px = 右 20px、下 30px
  • 混合:right 20px bottom 10px(四值語法,現代瀏覽器支援)

background-attachment 三值差異

值行為適用場景
scroll隨元素捲動(預設)一般內容區背景
fixed相對視窗固定視差滾動、全頁大圖、底部固定裝飾
local隨元素內容捲動可捲動容器內的背景圖案

⚠️ fixed 在 iOS Safari 早期版本有 Bug,現代版本已修復;移動端建議用 background-attachment: scroll + JS 視差或 position: sticky 替代。

縮寫寫法

/* 順序:color image repeat attachment position/size */
background: #f5f5f5 url("/images/bg.jpg") no-repeat fixed center bottom / cover;
/*                        ↑色彩  ↑圖片    ↑平鋪  ↑附著  ↑定位     ↑尺寸 */

實戰場景:頁尾固定裝飾帶

footer {
  position: relative;
  padding: 4rem 0;
  background: 
    linear-gradient(180deg, transparent, #fafafa 50%),
    url("/images/wave-bottom.svg") no-repeat center bottom / 100% auto;
  background-attachment: scroll; /* 移動端友善 */
}

延伸閱讀

掌握背景定位後,建議學習 CSS ID 與 Class 差異、用法與命名規範,建立清晰的樣式架構。

copyright © 萬盛學電腦網 all rights reserved