萬盛學電腦網

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

CSS 背景屬性完整指南:漸變、多背景、定位、縮寫與動畫

背景八大分屬性

屬性說明默認值
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);

CSS 漸變:現代背景圖替代

線性漸變

/* 方向關鍵字 */
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 */

background-size 關鍵字

  • 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;
}

clip vs origin 實戰區別

.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、內外邊距、邊框塌陷

copyright © 萬盛學電腦網 all rights reserved