| 屬性 | 說明 | 默認值 |
|---|---|---|
background-color | 背景色 | transparent |
background-image | 背景圖(含漸變) | none |
background-repeat | 平鋪方式 | repeat |
background-attachment | 固定/滾動 | scroll |
background-position | 初始位置 | 0% 0% |
background-size | 圖片尺寸 | auto |
background-clip | 繪製裁剪區 | border-box |
background-origin | 定位基準區 | padding-box |
/* 完整順序 */
background: color image repeat attachment position / size clip origin;
/* 實用常用簡寫 */
background: #f00 url(bg.png) no-repeat fixed center / cover;
/* 等同 */
background-color: #f00;
background-image: url(bg.png);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
多背景用逗號分隔,第一層在最上層:
background:
url(overlay.png) no-repeat center,
linear-gradient(45deg, #fff, #f0f0f0);
/* 方向關鍵字 */
background: linear-gradient(to right, #007bff, #00d4ff);
/* 角度 */
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
background: radial-gradient(circle at center, #fff, #007bff);
background: repeating-linear-gradient(
45deg, #fff, #fff 10px, #f0f0f0 10px, #f0f0f0 20px
);
/* 關鍵字 */
background-position: center top; /* 右下等 */
/* 百分比:相對 (容器尺寸 - 圖片尺寸) */
background-position: 50% 50%; /* 中心 */
/* 長度值:相對左上角 */
background-position: 20px 30px;
/* 四值語法:指定參考邊 + 偏移 */
background-position: right 20px bottom 30px; /* 右邊距 20px,底邊距 30px */
cover:覆蓋容器,保持比例,可能裁剪contain:完整包含圖片,保持比例,可能留白100% 100%:拉伸填滿,變形@keyframes slideBg {
0% { background-position: 0 0; }
100% { background-position: 1000px 0; }
}
.animated-bg {
background: linear-gradient(90deg, #007bff, #00d4ff, #007bff);
background-size: 200% 100%;
animation: slideBg 10s linear infinite;
}
.box {
border: 10px dashed red;
padding: 20px;
background: url(bg.png) no-repeat;
background-origin: content-box; /* 定位相對 content-box */
background-clip: padding-box; /* 裁剪到 padding-box,border 可見 */
}
CSS 盒模型尺寸計算:box-sizing、內外邊距、邊框塌陷