有一种方法来定位背景图像从其元素的右边一定数量的像素?
例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:
#myElement {
background-position: 10px 0;
}
有一种方法来定位背景图像从其元素的右边一定数量的像素?
例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:
#myElement {
background-position: 10px 0;
}
当前回答
最简单的解决方案是使用百分比。这并不是您想要的答案,因为您要求的是像素精度,但如果您只是需要在右边缘和图像之间有一些填充,那么给出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;
}
其他回答
过时的答案:它现在在主要浏览器中实现,请参阅 这个问题还有其他答案。
CSS3修改了背景位置的规格,使它可以在不同的原点上工作。不幸的是,我找不到任何证据表明它已经在任何主流浏览器中实现。
http://www.w3.org/TR/css3-background/#the-background-position 参见例12。
background-position: right 3em bottom 10px;
最简单的解决方案是使用百分比。这并不是您想要的答案,因为您要求的是像素精度,但如果您只是需要在右边缘和图像之间有一些填充,那么给出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: url('/img.png') no-repeat right center;
border-right: 10px solid transparent;
我之所以使用它,是因为浏览器还不太支持CSS3的特性,即在标记为解决问题的答案中指定偏移量。如。