有一种方法来定位背景图像从其元素的右边一定数量的像素?

例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:

#myElement {
    background-position: 10px 0;
}

当前回答

是的!好吧,把背景图片从浏览器的右边定位成0px,而不是左边-我使用:

background-position: 100% 0px;

其他回答

如果我明白你的要求你会这样做;

你有一个名为#main-container的DIV容器和其中的。my-element。用这个来开始吧;

#main-container { 
  position:relative;
}
/*To make the element absolute - floats above all else within the parent container do this.*/
.my-element {
  position:absolute;
  top:0;
  right:10px;
}

/*To make the element apart of elements, something tangible that affects the position of other elements on the same level within the parent then do this;*/
.my-element {
  float:right;
  margin-right:10px;
}

顺便说一下,如果您在页面中引用较低级别的元素,最好使用类(我假设您因此而更改了上面的名称)。

是的!好吧,把背景图片从浏览器的右边定位成0px,而不是左边-我使用:

background-position: 100% 0px;

我发现这个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/

更新:

现在所有主流浏览器都支持该功能,包括移动浏览器。

最合适的答案是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+ */
background-position: calc(100% - 8px);