background-position 的取值 有几种情况(在此之前请先去阅读关于background-origin的信息)
关键字: center top right bottom left(可以用百分比转换)
长度值: 这个长度值解释为 从内边距区左上角的偏移。便宜点是背景图像的左上角。
background-position: 20px 30px;
说明背景图像的左上角这个点 位于 距离元素内边距左上角点(起始位置)右边20像素,向下30像素的位置。(这里的前提是background-origin值是默认的padding-box,起始位置为padding-box的左上角。这个起始位置如果background-origin不同则会不同,请点击background-origin)
百分比: 其实the key of the article is the percentage.这个百分比并不是我们想象的背景图像的左上角的点,离元素的起始位置点的偏移。
按照《css权威指南的解释》就是百分数值同时应用于元素和背景图像。比如代码长这样:
p {
background-image: url(xxx.gif);
background-repeat: no-repeat;
background-position: 33% 66%;
}
这个xxx.gif的位置是在哪里? 可以这样说: 相对于背景图像来说,向右33%(背景图像的宽度), 向下66%(背景图像的高度)的这个点,与元素的内边距去左上角(默认background-origin为padding-box的起始位置)向右33%(元素的宽度), 向下66% (元素的高度)的这个点 是重合的!
还是mdn上的英文好理解的一点:
With a value pair of ‘0% 0%’, the upper left corner of the image is aligned with the upper left corner of the box’s padding edge. A value pair of ‘100% 100%’ places the lower right corner of the image in the lower right corner of padding area. With a value pair of ‘14% 84%’, the point 14% across and 84% down the image is to be placed at the point 14% across and 84% down the padding area.
tip: background-position会影响background-repeat的初始位置。
参考资料: MDN->background-position,《css权威指南》