在 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网站