body {
background: #f5f5f5 url(../images/bg.jpg) no-repeat bottom left;
/* IE 正常,Firefox/Chrome 背景圖不顯示 */
}
<body> 高度由內容撐開,若內容少於視窗高度,body 高度 < 視窗高度<html> 元素預設透明背景,視窗剩餘區域顯示畫布背景(通常白色)bottom left 相對 **body 邊界**,而非視窗body 底部,但 body 很短,圖片在可視區域之外html, body {
height: 100%; /* 關鍵:撐滿視窗高度 */
background: #f5f5f5 url(../images/bg.jpg) no-repeat bottom left;
margin: 0; padding: 0;
font-family: "Microsoft JhengHei", "SimSun", Arial, sans-serif;
font-size: 12px; color: #fff; text-align: left;
}
html, body { height: 100% } 強制根元素撐滿視窗html 與 body 兩層html 覆蓋整個視窗,背景圖按視窗底部定位 → 正確顯示body 背景作為備援,雙重保險html {
height: 100%;
background: #f5f5f5 url(../images/bg.jpg) no-repeat bottom left fixed; /* 固定背景 */
}
body {
min-height: 100%;
background: transparent; /* 透明,避免雙層疊加 */
}
html {
background-attachment: fixed; /* 視差效果基礎 */
background-size: cover; /* 響應式填滿 */
}
html {
background:
url(pattern.png) repeat 0 0,
url(hero.jpg) no-repeat center bottom,
#f5f5f5;
}
| 誤區 | 正確做法 |
|---|---|
| 只給 body 加 height:100% | html 也需 100%,否則 body 基準失效 |
| 用 min-height:100% | 需搭配 html height:100% 才生效 |
| 背景圖路徑相對 CSS 檔案 | 相對 HTML 頁面,建議用絕對路徑 /images/bg.jpg |
「Body 背景圖不顯示」實為 **文檔高度塌陷** 導致定位基準錯位。html, body { height: 100% } 雙重聲明是標準解法,現代專案更推薦 **單獨給 html 設定背景 + fixed/cover**,語意更清晰、效能更優、視覺效果更強。記住:背景圖的定位基準容器,必須有明確尺寸。