萬盛學電腦網

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

CSS background-position 定位技巧全解析:關鍵字、數值、百分比與負值實戰

定位參考系統

background-position 定義背景圖片相對容器的**初始位置**。預設 0 0(左上角)。坐標系統:

  • 原點:容器左上角(含 padding 區域)
  • X 軸:正右、負左
  • Y 軸:正下、負上

六大定位模式詳解

1. 關鍵字:left top(預設)

background-position: left top;   /* 等同 0 0、0% 0% */

圖片左上角對齊容器左上角。

2. 關鍵字:right bottom

background-position: right bottom;  /* 等同 100% 100% */

圖片右下角對齊容器右下角。等效計算:容器寬 - 圖片寬, 容器高 - 圖片高。

3. 正數值:500px 15px

background-position: 500px 15px;

圖片從容器左上角向右 500px、向下 15px。超出容器部分裁切。

4. 負數值:-500px -15px

background-position: -500px -15px;

圖片向左 500px、向上 15px 移動,**圖片右/下部分露出容器左/上區域** 。常用於 CSS Sprite 圖標定位。

5. 百分比:50% 50%(置中)

background-position: 50% 50%;  /* 等同 center center */

百分比計算公式:

實際位移 = (容器尺寸 - 圖片尺寸) × 百分比
  • 50%:(容器 - 圖片) × 0.5 → 圖片置中
  • 0%:貼齊左/上
  • 100%:貼齊右/下

這就是為何 50% 50% 能完美置中,而非單純「圖片中心對齊容器中心」。

6. 負百分比:-50% -50%

background-position: -50% -50%;

反方向位移:-(容器尺寸 - 圖片尺寸) × 百分比。極少用,但理解有助於掌握坐標系統本質。

CSS Sprite 實戰:負值定位圖標

.icon-set {
  background: url(sprite.png) no-repeat;
  width: 24px; height: 24px;
  display: inline-block;
}
.icon-home { background-position: 0 0; }
.icon-user { background-position: -24px 0; }
.icon-setting { background-position: -48px 0; }
.icon-mail { background-position: 0 -24px; }

單一圖片請求,負值精準切出各圖標,減少 HTTP 請求、提升載入速度。

進階技巧

四值語法(CSS Backgrounds Level 3)

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

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

支援關鍵字 + 長度/百分比組合,定位基準更靈活(IE9+、現代瀏覽器全支援)。

多背景獨立定位

.multi {
  background-image: url(logo.png), url(pattern.png);
  background-position: center top, 0 0;
  background-repeat: no-repeat, repeat;
}

動畫位移效果

@keyframes pan-bg {
  0% { background-position: 0 0; }
  100% { background-position: 100% 0; }
}
.animated-bg {
  background: url(panorama.jpg) repeat-x;
  background-size: auto 100%;
  animation: pan-bg 20s linear infinite;
}

常見坑點

  • 忘記 background-repeat: no-repeat:定位後仍平鋪,視覺錯亂
  • 容器無尺寸:百分比定位失效
  • 圖片未載入完成就計算:JS 動態插入圖片需 onload 後操作
  • 混淆 background-origin:預設 padding-box,可改 content-box/border-box

結語

background-position 看似簡單,實則蘊含「容器與圖片尺寸差值 × 百分比」的幾何邏輯。精通關鍵字、絕對值、百分比、負值四大模式,配合四值語法與 Sprite 技術,即能駕馭從圖標系統到全景視差的各類定位需求。

copyright © 萬盛學電腦網 all rights reserved