CSS 背景屬性

📢 本文由 gemini-2.5-flash 翻譯

背景屬性有以下這些

描述屬性
背景色background-color
背景圖background-image
背景圖平鋪方式background-repeat
背景圖位置background-position
背景圖縮放background-size
背景圖固定background-attachment
背景圖複合屬性background

背景圖

網頁中使用背景圖實現裝飾性的圖片效果

1
2
3
4
5
6
div {
    width: 500px;
    height: 300px;
    
    background-image: url(./img/00.jpg);
}

背景圖平鋪方式

background-repeat 有四個值

效果不平鋪平鋪 (預設)水平方向平鋪垂直方向平鋪
屬性值no-repeatrepeatrepeat-xrepeat-y

背景圖位置

background-position 的值為 水平方向位置 垂直方向位置 其中位置的值有關鍵字和座標

關鍵字有 left、right、center、top、bottom

座標使用 數字+px,正負皆可

1
2
3
4
5
div {
    background-position: center top;
    /* 也可以數字和單字混用 */
    /* background-position: -50px center; */
}

可以只寫一個關鍵字,另一個方向為置中;數字只寫一個為水平方向,垂直置中

背景圖縮放

background-size 常用三種屬性值

  • 關鍵字
    • cover:等比例縮放背景圖片以完全覆蓋背景區,可能圖片部分看不見
    • contain:等比例縮放背景圖片以完全裝入背景區,可能部分空白
  • 百分比:根據盒子尺寸計算圖片大小
  • 數字+單位 (如 px)

百分比為 100% 時圖片寬度和盒子寬度一致,高度等比例縮放

背景圖固定

background-attachment 使背景不會隨著元素的內容捲動,屬性值為 fixed

背景圖複合屬性

background 屬性值為 背景色 背景圖 背景圖平鋪方式 背景圖位置/背景圖縮放 背景圖固定 不區分順序

1
2
3
4
5
6
div {
    width: 500px;
    height: 500px;
    
    background: aqua url(./img/01.jpg) no-repeat center/cover;
}
This post is licensed under CC BY-NC-SA 4.0 by the author.