CSS 中的 background-repeat: no-repeat 專門用於控制背景圖片的重複行為。設定後,背景圖片將只顯示一次,不會像預設值 repeat 那樣在水平和垂直方向上無限平鋪。
.single-bg {
background-image: url('logo.png');
background-repeat: no-repeat;
/* 或使用簡寫 */
background: url('logo.png') no-repeat;
}
no-repeat 常搭配 background-position 使用,將單一背景圖片精確放置在容器的任意位置:
.positioned-bg {
background: url('icon.png') no-repeat;
/* 關鍵字定位 */
background-position: top center; /* 頂部居中 */
background-position: center center; /* 正中心 */
background-position: bottom right; /* 右下角 */
/* 精確像素定位 */
background-position: 20px 30px; /* 距左 20px、距頂 30px */
background-position: -10px 50%; /* 負值可讓圖片超出容器邊界 */
/* 百分比定位(響應式友好) */
background-position: 50% 50%; /* 等同 center center */
}
background-size: coverbackground-position 顯示大圖中的特定區塊| 屬性值 | 行為說明 |
|---|---|
repeat | 預設值,水平垂直雙向平鋪 |
repeat-x | 僅水平重複 |
repeat-y | 僅垂直重複 |
no-repeat | 不重複,僅顯示一次 |
space | 平鋪並均勻分佈空白(CSS3) |
round | 平鋪並縮放以填滿容器(CSS3) |
若容器尺寸小於背景圖片實際尺寸,圖片會被截取;配合 background-size: contain 或 cover 可獲得更好的自適應效果。