有一种方法来定位背景图像从其元素的右边一定数量的像素?
例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:
#myElement {
background-position: 10px 0;
}
有一种方法来定位背景图像从其元素的右边一定数量的像素?
例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:
#myElement {
background-position: 10px 0;
}
当前回答
我发现这个CSS3特性很有用:
/* to position the element 10px from the right */
background-position: right 10px top;
据我所知,IE8不支持这个功能。在最新的Chrome/Firefox中,它工作得很好。
有关受支持的浏览器的详细信息,请参阅我是否可以使用。
使用来源:http://tanalin.com/en/blog/2011/09/css3-background-position/
更新:
现在所有主流浏览器都支持该功能,包括移动浏览器。
其他回答
使用中心右边的位置,然后添加一个透明的边界来抵消它?
CSS3规范允许背景位置的不同来源现在在Firefox 14中得到支持,但在Chrome 21中仍然不支持(显然IE9部分支持它们,但我自己没有测试过)
除了@MattyF提到的Chrome问题之外,这里还有一个更简洁的总结: http://code.google.com/p/chromium/issues/detail?id=95085
最简单的解决方案是使用百分比。这并不是您想要的答案,因为您要求的是像素精度,但如果您只是需要在右边缘和图像之间有一些填充,那么给出99%的位置通常就足够了。
代码:
/* aligns image to the vertical center and horizontal right of its container with a small amount of padding between the right edge */
div.middleleft {
background: url("/images/source.jpg") 99% center no-repeat;
}
最合适的答案是background-position的新四值语法,但在所有浏览器都支持它之前,最好的方法是按照以下顺序组合之前的响应:
background: url(image.png) no-repeat 97% center; /* default, Android, Sf < 6 */
background-position: -webkit-calc(100% - 10px) center; /* Sf 6 */
background-position: right 10px center; /* Cr 25+, FF 13+, IE 9+, Op 10.5+ */
我发现这个CSS3特性很有用:
/* to position the element 10px from the right */
background-position: right 10px top;
据我所知,IE8不支持这个功能。在最新的Chrome/Firefox中,它工作得很好。
有关受支持的浏览器的详细信息,请参阅我是否可以使用。
使用来源:http://tanalin.com/en/blog/2011/09/css3-background-position/
更新:
现在所有主流浏览器都支持该功能,包括移动浏览器。