<div> 是最通用的區塊級容器,本身無語意,常作為版面區塊、元件包裹器。設定背景色是建立視覺層次、區隔內容區域的基本技能。本文從單一顏色到漸層、圖片、多重背景,系統整理 background 相關技術。
<style>
.divcss5 {
background-color: #f00; /* 紅色背景 */
color: #fff; /* 白色文字,確保對比度 */
padding: 20px; /* 內距避免文字貼邊 */
}
</style>
<div class="divcss5">背景色為紅色</div>
.box {
/* 速寫順序(任意順序皆可,但建議固定順序) */
background:
#f0f0f0 /* background-color: 備援色 */
url("texture.png") /* background-image: 圖片 */
no-repeat /* background-repeat */
center center /* background-position */
/ cover /* background-size (需用 / 分隔) */
fixed /* background-attachment */
padding-box /* background-origin */
content-box; /* background-clip */
}
background-color支援所有 CSS 色彩格式:關鍵字、十六進位、rgb/rgba、hsl/hsla。建議永遠設定備援色,防圖片載入失敗或透明區域露白。
background-image.hero {
background-image:
linear-gradient(135deg, #667eea 0%, #764ba2 100%),
url("hero.jpg"); /* 多重背景:第一層在最上層 */
}
background-repeat| 值 | 效果 |
|---|---|
repeat | 水平垂直平鋪(預設) |
repeat-x | 僅水平平鋪 |
repeat-y | 僅垂直平鋪 |
no-repeat | 不平鋪 |
space | 平鋪並均勻分佈空白 |
round | 平鋪並縮放填滿 |
background-position/* 關鍵字 */
background-position: center top;
background-position: right bottom;
/* 百分比(容器尺寸 - 圖片尺寸)的百分比 */
background-position: 50% 50%; /* 置中 */
/* 像素/長度單位 */
background-position: 20px 30px;
/* 四值語法(指定參考邊) */
background-position: right 20px bottom 10px;
background-size| 值 | 說明 |
|---|---|
auto | 原始尺寸(預設) |
cover | 覆蓋整個容器,保持比例,可能裁切 |
contain | 完整顯示圖片,保持比例,可能留白 |
100% 100% | 拉伸填滿,不保持比例 |
200px 100px | 指定寬高 |
background-attachment| 值 | 行為 |
|---|---|
scroll | 隨元素內容捲動(預設) |
fixed | 固定於視口,視差滾動效果基礎 |
local | 隨元素內容捲動(針對可捲動容器) |
background-clip vs 定位區域 background-origin.demo {
border: 10px dashed #333;
padding: 20px;
background-image: url("pattern.png");
/* origin: 定位參考框 */
background-origin: padding-box; /* 預設:從 padding 邊緣開始定位 */
/* background-origin: border-box; */ /* 從 border 邊緣 */
/* background-origin: content-box; */ /* 從 content 邊緣 */
/* clip: 實際繪製裁切框 */
background-clip: padding-box; /* 預設:繪製到 padding 邊緣 */
/* background-clip: border-box; */ /* 繪製到 border 邊緣(含 border 下方) */
/* background-clip: content-box; */ /* 僅繪製在 content 區域 */
/* background-clip: text; */ /* 文字裁切,配合 text-fill-color: transparent */
}
.card {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
transition: box-shadow 0.3s;
}
.card:hover { box-shadow: 0 8px 24px rgba(0,0,0,0.12); }
.hero {
min-height: 400px;
background:
linear-gradient(135deg, rgba(102,126,234,0.9), rgba(118,75,162,0.9)),
url("hero-bg.jpg") center/cover no-repeat;
display: flex; align-items: center; justify-content: center;
color: #fff; text-align: center;
}
.striped {
background: repeating-linear-gradient(
45deg,
#f0f0f0 0, #f0f0f0 10px,
#e8e8e8 10px, #e8e8e8 20px
);
}
loading="lazy"、CDN 加速。fixed 在移動端:iOS Safari 早期有重繪效能問題,現代版本改善但仍需測試。掌握 background 全屬性組合,能讓你用最少的 DOM 結構創造豐富視覺效果。從簡單的顏色填充到複雜的多層漸層疊加,背景技術是 CSS 表現力的核心支柱之一。