有一种方法来定位背景图像从其元素的右边一定数量的像素?
例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:
#myElement {
background-position: 10px 0;
}
有一种方法来定位背景图像从其元素的右边一定数量的像素?
例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:
#myElement {
background-position: 10px 0;
}
当前回答
最合适的答案是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+ */
其他回答
最简单的解决方案是使用百分比。这并不是您想要的答案,因为您要求的是像素精度,但如果您只是需要在右边缘和图像之间有一些填充,那么给出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: calc(100% - 8px);
最合适的答案是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+ */
这将适用于大多数现代浏览器…除了IE(浏览器支持)。尽管该页面列出了支持>= IE9,但我的测试并不同意这一点。
你可以像这样使用calc() css3属性;
.class_name {
background-position: calc(100% - 10px) 50%;
}
对我来说,这是最干净、最合乎逻辑的方式来实现向右的边缘。我还使用了border-right: 10px solid transparent;IE。
如果你有一个固定宽度的元素,并且知道你的背景图像的宽度,你可以简单地设置background-position为:元素的宽度-图像的宽度-你想要在右边的间隙。
例如:对于一个100px宽的元素和一个300px宽的图像,要在右侧获得10px的间隙,您将其设置为100-300-10=-210px:
#myElement {
background:url(my_image.jpg) no-repeat -210px top;
width:100px;
}
你在元素的左边得到了图像最右边的80像素,在右边有一个20px的间隙。
我知道这听起来很愚蠢,但有时它节省了时间……我用垂直的方式(在底部的差距)导航链接与文字下面的图像。
但不确定这适用于你的案子。