CSS 背景圖片的定位和縮放

在 CSS 中,利用 background-image 屬性咱們能夠指定元素的背景圖片,例如:css

.example {
  background-image: url(image/some.png);
  background-repeat: repeat;
}

其中,PNG 是常見的背景圖片格式;較新的瀏覽器,好比 Chrome 8+,Firefox 4+,IE 9+,Opera 9.5+ 和 Safari 5+,也支持使用 SVG 格式的背景圖片。當背景圖片大小超過元素的大小時,咱們能夠用 background-repeat 屬性指明重複覆蓋的方式。html

一般,一個網站中會使用許多個小圖片。爲減小網絡請求的數目,咱們常常將多個小圖片拼合爲一個大圖片,而後用 CSS Sprite 的方法,截取其中的某個圖片。假設咱們將 5 個寬爲 24px 的小圖片,從左到右合併爲一個寬爲 120px 的大圖片。此時,咱們能夠用下面的方法,分別截取出第 2 個和第 3 個小圖片做爲背景:css3

.image2 {
  background-image: url(some.png);
  background-repeat: no-repeat;
  background-position: -24px 0px;
}
.image3 {
  background-image: url(some.png);
  background-repeat: no-repeat;
  background-position: -48px 0px;
}

其中,background-position 屬性指明瞭背景圖片的左上角位置相對於元素區域的左上角的偏移值。瀏覽器

這個 background-position 屬性也能夠使用比例值,此時表示背景圖片的該比例位置和元素區域的該比例位置重合。所以,取值爲 0% 0% 表示背景圖片的左上角和元素區域的左上角重合,而取值爲 50% 50% 表示背景圖片的中心和元素區域的中心重合。上面的例子也能夠改成比例值以下:網絡

.image2 {
  background-image: url(some.png);
  background-repeat: no-repeat;
  background-position: 25% 0%;
}
.image3 {
  background-image: url(some.png);
  background-repeat: no-repeat;
  background-position: 50% 0%;
}

通過簡單計算可知,若是一行有 n 個等寬的圖片,則截取第 k 個時要用的比例值爲 (k-1)/(n-1)。不過使用比例值有時也不太可靠,例如在 Opera 12.15 中測試時發現,使用長度值時截取正常,而使用比例值時截取有些錯位。dom

有時候,咱們也會須要從大圖片中先縮小到必定大小,再截取部分圖片。這時候能夠用 CSS3 的 background-size 屬性。例如,咱們用 SVG 圖形做爲背景圖片,其中該 SVG 圖形中包含 5 排 3 列共 15 個 96x96 像素的小圖形,總共大小爲 480x288 像素。而咱們須要截取第 2 個和第 3 個並縮放到 24x24 像素大小做爲背景圖片。此時的 CSS 代碼以下:svg

.image2 {
  width: 24px; height: 24px;
  background-image: url(some.svg);
  background-repeat: no-repeat;
  background-size: 120px 72px;
  background-position: -24px 0px;
}
.image3 {
  width: 24px; height: 24px;
  background-image: url(some.svg);
  background-repeat: no-repeat;
  background-size: 500% 300%;
  background-position: -48px 0px;
}

其中,咱們先用 background-size 屬性將 some.svg 縮小到 120x72 像素,再用 background-position 屬性截取小圖片。這個 background-size 屬性既能夠用長度值也能夠用比例值,用比例值時將根據元素的大小計算背景圖片的縮放大小。Chrome 3+,Firefox 4+,IE 9+,Opera 10+ 和 Safari 4.1+ 都支持這個屬性。測試

參考資料:
[1] MDN - background-image - CSS
[2] MDN - background-repeat - CSS
[3] MDN - background-position - CSS
[4] MDN - background-size - CSS
[5] W3C - CSS2 - Colors and Backgrounds
[6] W3C - CSS Backgrounds and Borders Module Level 3
[7] CSS: Using Percentages in Background-Image - SitePoint
[8] svg-icon-loader - load SVG images from one single file
[9] SVG CSS Injection—A Different Approach Towards SVG Rendering網站

相關文章
相關標籤/搜索