文章

顏色和背景

顏色和背景

CSS 提供了多種方式來設定網頁元素的顏色和背景。透過使用這些屬性,我們可以設計出更吸引人的網頁。以下是 CSS 中控制顏色和背景的常用屬性和方法。

1. 顏色屬性(color

color 屬性用於設定文字的顏色。可以使用顏色名稱(如 red)、十六進位顏色值(如 #ff0000)、RGB 顏色值(如 rgb(255, 0, 0))、RGBA 顏色值(如 rgba(255, 0, 0, 0.5)),以及 HSL 顏色值(如 hsl(0, 100%, 50%))來指定顏色。

  • 語法
    1
    
    color: 顏色值;
    
  • 範例
    1
    2
    3
    4
    5
    6
    
    p {
        color: #333; /* 十六進位顏色 */
    }
    .highlight {
        color: rgb(255, 0, 0); /* 紅色 */
    }
    

2. 背景顏色(background-color

background-color 屬性用於設定元素的背景顏色。

  • 語法
    1
    
    background-color: 顏色值;
    
  • 範例
    1
    2
    3
    4
    5
    6
    
    div {
        background-color: lightblue;
    }
    .notice {
        background-color: rgba(255, 255, 0, 0.3); /* 使用 RGBA 設置透明背景 */
    }
    

3. 背景圖片(background-image

background-image 屬性用於在元素的背景中設置一個圖片。常用於製作背景圖案、紋理或其他視覺效果。

  • 語法
    1
    
    background-image: url('圖片網址');
    
  • 範例
    1
    2
    3
    
    body {
        background-image: url('background.jpg');
    }
    
  • 註:使用 background-image 時,圖片路徑可以是相對路徑或絕對路徑。

4. 背景重複(background-repeat

background-repeat 屬性用於定義背景圖片的重複方式。

  • 屬性值
    • repeat:在水平和垂直方向上重複(預設值)。
    • repeat-x:僅在水平方向重複。
    • repeat-y:僅在垂直方向重複。
    • no-repeat:不重複。
  • 語法
    1
    
    background-repeat: repeat-x;
    
  • 範例
    1
    2
    3
    4
    
    header {
        background-image: url('header-pattern.png');
        background-repeat: no-repeat;
    }
    

5. 背景位置(background-position

background-position 屬性用於設定背景圖片在元素中的起始位置。

  • 屬性值
    • 可以使用關鍵字(如 topcenterbottomleftright)或具體的像素/百分比值(如 10px 20px50% 50%)。
  • 語法
    1
    
    background-position: center center;
    
  • 範例
    1
    2
    3
    4
    
    section {
        background-image: url('section-bg.jpg');
        background-position: center;
    }
    

6. 背景大小(background-size

background-size 屬性用於設定背景圖片的大小。

  • 屬性值
    • auto:保持圖片的原始尺寸(預設值)。
    • cover:圖片擴展以完全覆蓋元素的背景區域,但可能會超出容器。
    • contain:圖片擴展以適應元素的背景區域,但保持圖片的寬高比。
    • 具體的尺寸值(如 100px50%)。
  • 語法
    1
    
    background-size: cover;
    
  • 範例
    1
    2
    3
    4
    
    div.banner {
        background-image: url('banner.jpg');
        background-size: cover;
    }
    

7. 背景附件(background-attachment

background-attachment 屬性用於設定背景圖片是固定的還是隨著頁面滾動。

  • 屬性值
    • scroll:背景圖片會隨著頁面滾動(預設值)。
    • fixed:背景圖片固定,不會隨著頁面滾動。
    • local:背景圖片會隨著元素的內容滾動。
  • 語法
    1
    
    background-attachment: fixed;
    
  • 範例
    1
    2
    3
    4
    
    body {
        background-image: url('fixed-bg.jpg');
        background-attachment: fixed;
    }
    

8. 簡寫屬性(background

background 是一個簡寫屬性,用於一次性定義背景的多個屬性。

  • 語法
    1
    
    background: [背景顏色] [背景圖片] [重複方式] [附件] [位置];
    
  • 範例
    1
    2
    3
    
    body {
        background: #f0f0f0 url('bg-pattern.png') no-repeat fixed center;
    }
    

小結

使用顏色和背景屬性可以大大增強網頁的視覺吸引力。通過靈活運用這些屬性,我們可以創建出不同的設計效果,從簡單的顏色設置到複雜的背景圖案和動畫效果。掌握這些屬性將有助於設計出更具吸引力和易用性的網頁。

本文章以 CC BY 4.0 授權