| 值 | 行為 | 適用場景 |
|---|---|---|
repeat | 水平垂直雙向平鋪(預設) | 紋理、圖案背景 |
repeat-x | 僅水平平鋪 | 水平漸層條、頂部裝飾帶 |
repeat-y | 僅垂直平鋪 | 側邊欄邊框、垂直分隔線 |
no-repeat | 不平鋪,僅顯示一次 | Logo、Hero Banner、裝飾圖示 |
space | 平鋪並均勻分佈間距(不裁切) | 圖示網格、邊框裝飾 |
round | 平鋪並縮放以填滿(可能軟微變形) | 自適應重複圖案 |
搭配 background-position 精確控制單一背景圖位置:
.hero {
background: url('banner.jpg') no-repeat center center / cover;
/* 等價於 */
background-image: url('banner.jpg');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
}
| 關鍵字 | 等值座標 | 說明 |
|---|---|---|
top left / left top | 0 0 / 0% 0% | 左上角 |
top center / center top | 50% 0 | 上方置中 |
top right / right top | 100% 0 | 右上角 |
center left / left center | 0 50% | 左側置中 |
center center / center | 50% 50% | 正中心 (預設) |
center right / right center | 100% 50% | 右側置中 |
bottom left / left bottom | 0 100% | 左下角 |
bottom center / center bottom | 50% 100% | 下方置中 |
bottom right / right bottom | 100% 100% | 右下角 |
.icon {
background: url('sprite.png') no-repeat -20px -40px; /* Sprite 定位 */
}
.watermark {
background: url('logo.png') no-repeat right 20px bottom 15px; /* 四值語法:從右/下偏移 */
}
background: [color] [image] [repeat] [attachment] [position] [/ size] [origin] [clip];
/* 完整範例 */
background: #f0f0f0 url('bg.png') no-repeat fixed center center / cover content-box padding-box;
/* 色彩 圖片 不重複 固定定位 置中置中 覆蓋 定位區域 裁切區域 */
可省略任意值,瀏覽器套用預設:transparent none repeat scroll 0% 0%。
.multi-bg {
background:
url('icon.png') no-repeat left top,
url('pattern.png') repeat center center,
linear-gradient(135deg, #667eea, #764ba2);
/* 第一層在最上層,最後一層在最底層 */
}
.hero {
min-height: 100vh;
background: url('hero.jpg') no-repeat center center / cover;
position: relative;
}
.hero::before {
content: '';
position: absolute; inset: 0;
background: rgba(0,0,0,0.4); /* 深色遮罩提升文字可讀性 */
}
.card {
padding-left: 48px;
background: url('icon-check.svg') no-repeat left center / 24px;
background-size: 24px 24px;
}
.parallax {
background: url('bg.jpg') no-repeat center center / cover;
background-attachment: fixed; /* 視差滾動效果 */
min-height: 400px;
}
background-size: cover 避免圖片拉伸變形<link rel="preload" as="image">body 使用大圖固定定位,會導致捲動卡頓