萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS Background 背景屬性完整指南:縮寫語法、多重背景、漸層、固定附著與響應式技巧

背景屬性完整清單

屬性說明預設值
background-color背景色transparent
background-image背景圖片/漸層none
background-repeat平鋪模式repeat
background-attachment捲動/固定scroll
background-position定位位置0% 0% (left top)
background-size縮放大小auto
background-origin定位基準區域padding-box
background-clip繪製裁切區域border-box

縮寫語法(單一背景)

/* 順序:color image repeat attachment position / size */
background: #f5f5f5 url("bg.jpg") no-repeat fixed center top / cover;

/* 等效展開 */
background-color: #f5f5f5;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center top;
background-size: cover; 

多重背景(Modern CSS,逗號分隔,先寫在上層)

.hero {
  background: 
    /* 第 1 層:裝飾性幾何圖案 */
    url("pattern.svg") repeat center / 200px,
    /* 第 2 層:漸層覆蓋 */
    linear-gradient(135deg, rgba(102,126,234,.9), rgba(118,75,162,.9)),
    /* 第 3 層:大圖底圖 */
    url("hero.jpg") no-repeat center / cover;
  
  /* 等效展開寫法(較易維護) */
  background-image: 
    url("pattern.svg"),
    linear-gradient(135deg, rgba(102,126,234,.9), rgba(118,75,162,.9)),
    url("hero.jpg");
  background-repeat: repeat, no-repeat, no-repeat;
  background-position: center, center, center;
  background-size: 200px, cover, cover;
  background-attachment: scroll, fixed, scroll;
}

漸層語法速查

/* 線性漸層 */
linear-gradient(135deg, #667eea 0%, #764ba2 100%)
linear-gradient(to right, red, blue)
linear-gradient(45deg, red 0%, orange 25%, yellow 50%, green 75%, blue 100%)

/* 徑向漸層 */
radial-gradient(circle at center, #fff, #000)
radial-gradient(ellipse 50% 50% at 50% 50%, #fff, #000)

/* 重複漸層(圖案) */
repeating-linear-gradient(45deg, #fff 0, #fff 10px, #eee 10px, #eee 20px)
repeating-radial-gradient(circle, #fff, #fff 10px, #eee 10px, #eee 20px)

背景定位進階:四值語法

/* 從右邊 20px、底部 30px 定位 */
background-position: right 20px bottom 30px;

/* 從左邊 10%、頂部 2em 定位 */
background-position: left 10% top 2em; 

實戰常見模式

全螢幕 Hero 區塊(固定視差感)

.hero {
  min-height: 100vh;
  background: url("hero.jpg") no-repeat center / cover;
  background-attachment: fixed; /* 桌面視差 */
  display: flex; align-items: center; justify-content: center;
}
@media (max-width: 768px) {
  .hero { background-attachment: scroll; } /* 移動端關閉 fixed 避免效能/定位問題 */
}

CSS-only 圖案背景(零圖片請求)

.pattern-dots {
  background-color: #f0f4f8;
  background-image: radial-gradient(circle, #cbd5e1 1px, transparent 1px);
  background-size: 20px 20px;
}
.pattern-stripes {
  background: repeating-linear-gradient(
    45deg, transparent, transparent 10px, 
    rgba(0,0,0,.03) 10px, rgba(0,0,0,.03) 20px
  );
}

背景圖片載入優化

  • background-size: cover 配合 srcset / image-set() 多解析度
  • 關鍵背景圖 <link rel="preload" as="image">
  • 非首屏背景 loading="lazy"(需 JS 觀察器配合)

延伸閱讀

掌握背景技巧後,建議學習 CSS Border 邊框屬性完整指南,完成盒模型視覺控制。

copyright © 萬盛學電腦網 all rights reserved