Skip to main content

CSS 背景介紹

CSS 背景屬性用於控制 HTML 元素的背景樣式,例如顏色、圖片、圖片位置、大小等。以下是常見的背景屬性及其用途,搭配詳細的 CSS 範例,方便你作為前端工程師理解並直接應用。所有範例均使用純 CSS 寫法,並以台灣慣用的表達方式呈現。

1. background-color:設置背景顏色

用於定義元素的背景顏色,可以使用顏色名稱、十六進位值、RGB、RGBA 或 HSL。

/* 範例:設置背景為淺藍色 */
.element {
background-color: #87CEEB;
}

/* 範例:使用 RGBA 設置半透明紅色 */
.element {
background-color: rgba(255, 0, 0, 0.5);
}

2. background-image:設置背景圖片

用於為元素添加背景圖片,需提供圖片的 URL。

/* 範例:添加背景圖片 */
.element {
background-image: url('https://example.com/image.jpg');
}

3. background-repeat:控制背景圖片是否重複

可選值包括 repeat(預設,水平垂直重複)、repeat-x(僅水平重複)、repeat-y(僅垂直重複)、no-repeat(不重複)。

/* 範例:背景圖片不重複 */
.element {
background-image: url('https://example.com/image.jpg');
background-repeat: no-repeat;
}

/* 範例:僅水平重複 */
.element {
background-image: url('https://example.com/image.jpg');
background-repeat: repeat-x;
}

4. background-position:設置背景圖片位置

控制背景圖片在元素中的位置,可以使用關鍵字(如 top、center)、百分比或具體像素值。

/* 範例:背景圖片置中 */
.element {
background-image: url('https://example.com/image.jpg');
background-repeat: no-repeat;
background-position: center;
}

/* 範例:背景圖片位於左上角 10px 處 */
.element {
background-image: url('https://example.com/image.jpg');
background-repeat: no-repeat;
background-position: 10px 10px;
}

5. background-size:設置背景圖片大小

控制背景圖片的大小,可用關鍵字(如 auto、cover、contain)或具體尺寸。

  • auto:保持圖片原始大小

  • cover:縮放圖片填滿容器,可能裁切

  • contain:縮放圖片適應容器,可能留白

/* 範例:背景圖片填滿容器 */
.element {
background-image: url('https://example.com/image.jpg');
background-repeat: no-repeat;
background-size: cover;
}

/* 範例:固定寬高 */
.element {
background-image: url('https://example.com/image.jpg');
background-repeat: no-repeat;
background-size: 200px 100px;
}

6. background-attachment:控制背景圖片是否隨滾動條移動

可選值包括 scroll(預設,隨元素滾動)、fixed(固定於視窗)、local(隨內容滾動)。

/* 範例:背景圖片固定不隨滾動條移動 */
.element {
background-image: url('https://example.com/image.jpg');
background-attachment: fixed;
}

7. background:縮寫屬性

可以用單一屬性同時設置多個背景屬性,順序通常為:background-color、background-image、background-repeat、background-attachment、background-position。

/* 範例:縮寫設置背景 */
.element {
background: #f0f0f0 url('https://example.com/image.jpg') no-repeat center fixed;
}

8. 多重背景

CSS 允許為單一元素設置多個背景圖片,圖片間用逗號分隔,層疊順序由前到後。

/* 範例:設置兩個背景圖片 */
.element {
background:
url('https://example.com/image1.jpg') no-repeat top left,
url('https://example.com/image2.jpg') no-repeat bottom right;
background-color: #ffffff;
}

9. 背景漸層(Linear Gradient)

使用 linear-gradient() 創建線性漸層作為背景。

/* 範例:從上到下由紅色漸層到藍色 */
.element {
background: linear-gradient(to bottom, red, blue);
}

/* 範例:45度角漸層 */
.element {
background: linear-gradient(45deg, yellow, green);
}

10. 背景透明與不透明

使用 background-color 的 RGBA 或 opacity 控制背景透明度。

/* 範例:半透明背景 */
.element {
background-color: rgba(0, 128, 0, 0.3);
}

注意事項

  • 確保圖片 URL 正確,否則背景圖片無法顯示。

  • 背景屬性縮寫時,順序不強制,但建議保持一致以提高可讀性。

  • 背景圖片與顏色可以同時存在,圖片會覆蓋在顏色之上。

  • 測試不同螢幕尺寸,確保 background-size 和 background-position 適配響應式設計。