【问题标题】:Css background position coordinatesCSS背景位置坐标
【发布时间】:2012-12-13 13:02:49
【问题描述】:
我想用这张图片制作 css sprite
我的html代码;
<div class="top"></div>
<div class="bottom"></div>
<div class="right"></div>
<div class="left"></div>
还有css代码;
.left{
background : url(arrw.png) no-repeat 0 0;
width:12px;
height:19px;
}
.right{
background : url(arrw.png) no-repeat -29px 0;
width:12px;
height:19px;
}
.top{
background : url(arrw.png) no-repeat -12px 0;
width:16px;
height:12px;
}
.bottom{
background : url(arrw.png) no-repeat -12px -12px;
width:16px;
height:12px;
}
效果很好,但我不明白为什么要为背景位置提供负值。这不是坐标系统吗?难道我们没有必要为此给出正值吗?位置值从 0 0(左上角)开始,必须取正值不是吗?有什么问题?
【问题讨论】:
标签:
css
position
background-image
css-sprites
background-position
【解决方案1】:
您使用的精灵图像通常比您显示它们的框大。如果只包含一张图片,它将被定位在左上角。现在,如果要显示溢出到框右侧的图像部分,则需要将图像移动到左侧。但由于默认情况下图像已经位于left: 0;,因此您需要设置负值以将其进一步向左移动。
想想两张纸,一张有洞,另一张在第一张后面移动。要查看位于其右下角的后页的一部分,您需要移动到左上角。因此,当您通过孔看到后页/在框中显示图像时,位置方向与您想要移动后页的方向相反。
【解决方案2】:
好的,取一个位置为 0 0 的背景图像的 div。添加到它,你向下和向右移动它。减法将其向上和向左移动。 0 0 是该系统的基础。
如果这让您感到厌烦,您可以将代码更改为:
.left{
background : url(arrw.png) no-repeat top left;
width:12px;
height:19px;
}
.right{
background : url(arrw.png) no-repeat top right;
width:12px;
height:19px;
}
.top{
background : url(arrw.png) no-repeat top center;
width:16px;
height:12px;
}
.bottom{
background : url(arrw.png) no-repeat bottom center;
width:16px;
height:12px;
}