萬盛學電腦網

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

CSS background-repeat: no-repeat 完整解析:背景圖片不重複的控制與定位技巧

background-repeat 核心值

值行為適用場景
repeat水平垂直雙向平鋪(預設)紋理、圖案背景
repeat-x僅水平平鋪水平漸層條、頂部裝飾帶
repeat-y僅垂直平鋪側邊欄邊框、垂直分隔線
no-repeat不平鋪,僅顯示一次Logo、Hero Banner、裝飾圖示
space平鋪並均勻分佈間距(不裁切)圖示網格、邊框裝飾
round平鋪並縮放以填滿(可能軟微變形)自適應重複圖案

no-repeat 定位控制

搭配 background-position 精確控制單一背景圖位置:

.hero {
  background: url('banner.jpg') no-repeat center center / cover;
  /* 等價於 */
  background-image: url('banner.jpg');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

定位寫法對照

關鍵字等值座標說明
top left / left top0 0 / 0% 0%左上角
top center / center top50% 0上方置中
top right / right top100% 0右上角
center left / left center0 50%左側置中
center center / center50% 50%正中心 (預設)
center right / right center100% 50%右側置中
bottom left / left bottom0 100%左下角
bottom center / center bottom50% 100%下方置中
bottom right / right bottom100% 100%右下角

數值定位(像素/百分比/負值)

.icon {
  background: url('sprite.png') no-repeat -20px -40px;  /* Sprite 定位 */
}

.watermark {
  background: url('logo.png') no-repeat right 20px bottom 15px;  /* 四值語法:從右/下偏移 */
}

background 縮寫屬性順序

background: [color] [image] [repeat] [attachment] [position] [/ size] [origin] [clip];

/* 完整範例 */
background: #f0f0f0 url('bg.png') no-repeat fixed center center / cover content-box padding-box;
/*  色彩     圖片      不重複   固定定位   置中置中  覆蓋   定位區域  裁切區域 */

可省略任意值,瀏覽器套用預設:transparent none repeat scroll 0% 0%。

多重背景(CSS3)

.multi-bg {
  background: 
    url('icon.png') no-repeat left top,
    url('pattern.png') repeat center center,
    linear-gradient(135deg, #667eea, #764ba2);
  /* 第一層在最上層,最後一層在最底層 */
}

實務應用場景

1. Hero Banner 全螢幕背景

.hero {
  min-height: 100vh;
  background: url('hero.jpg') no-repeat center center / cover;
  position: relative;
}
.hero::before {
  content: '';
  position: absolute; inset: 0;
  background: rgba(0,0,0,0.4);  /* 深色遮罩提升文字可讀性 */
}

2. 卡片裝飾圖示

.card {
  padding-left: 48px;
  background: url('icon-check.svg') no-repeat left center / 24px;
  background-size: 24px 24px;
}

3. 固定背景視差效果

.parallax {
  background: url('bg.jpg') no-repeat center center / cover;
  background-attachment: fixed;  /* 視差滾動效果 */
  min-height: 400px;
}

效能與最佳實踐

  • 大型背景圖必須壓縮(WebP/AVIF)、適當尺寸(≤1920px 寬)
  • 使用 background-size: cover 避免圖片拉伸變形
  • 關鍵背景圖加入 <link rel="preload" as="image">
  • 避免在 body 使用大圖固定定位,會導致捲動卡頓
  • 多重背景按重要性排序,前景層優先載入
copyright © 萬盛學電腦網 all rights reserved