萬盛學電腦網

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

CSS 背景圖片定位底部:background-position 底部對齊完整寫法

前言

需求:背景圖片固定在容器底部顯示,不隨內容捲動(或捲動)。本文提供兩種寫法:縮寫屬性與拆解屬性,並說明各屬性作用。

方法一:背景縮寫屬性(推薦,簡潔)

.bottom-bg {
  background: url(/images/bg.jpg) no-repeat fixed center bottom;
  /* 顏色 圖片 重複 固定 水平位置 垂直位置 */
}

參數順序:color image repeat attachment position-x position-y。省略值採用預設。

方法二:拆解屬性寫法(語義明確,易維護)

.bottom-bg {
  background-image: url(/images/bg.jpg);   /* 設定圖片 */
  background-repeat: no-repeat;            /* 不重複 */
  background-attachment: fixed;            /* 固定視窗,不隨內容捲動 */
  background-position-x: center;           /* 水平置中 */
  background-position-y: bottom;           /* 垂直靠底 */
  /* background-attachment: scroll; */     /* 隨內容捲動(預設) */
}

屬性值完整對照表

屬性常用值說明
background-repeatrepeat、repeat-x、repeat-y、no-repeat平鋪方式
background-attachmentscroll、fixed、local捲動行為
background-position-xleft、center、right、長度、百分比水平位置
background-position-ytop、center、bottom、長度、百分比垂直位置

進階應用:多背景層疊

.multi-bg {
  background: 
    url(icon.png) no-repeat left top,      /* 第1層:左上圖示 */
    url(pattern.png) repeat center center, /* 第2層:中間紋理 */
    url(bg.jpg) no-repeat center bottom;   /* 第3層:底部大圖 */
  background-color: #f0f0f0; /* 兜底色 */
}

多背景按書寫順序疊加,第一層最上層。

響應式背景尺寸控制

.responsive-bg {
  background: url(bg.jpg) no-repeat center bottom;
  background-size: cover;      /* 覆蓋容器,可能裁切 */
  /* background-size: contain; */ /* 完整顯示,可能留白 */
  /* background-size: 100% auto; */ /* 寬度滿容器,高度自適應 */
  min-height: 300px; /* 確保有空間顯示 */
}

結語

背景圖片底部對齊核心在於 background-position-y: bottom(或縮寫 center bottom)。搭配 background-size: cover 與 min-height,即可實現跨裝置自適應的底部背景效果。

copyright © 萬盛學電腦網 all rights reserved