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

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

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

当前回答

background-position: calc(100% - 8px);

其他回答

如果你想使用这个添加箭头/其他图标到一个按钮,那么你可以使用css伪元素?

如果它真的是整个按钮的背景图像,我倾向于将间距合并到图像中,并使用

background-position: right 0;

但如果我必须添加一个设计的箭头到一个按钮,我倾向于有这样的html:

<a href="[url]" class="read-more">Read more</a>

并倾向于用CSS做以下事情:

.read-more{
    position: relative;
    padding: 6px 15px 6px 35px;//to create space on the right
    font-size: 13px;
    font-family: Arial;
}

.read-more:after{
    content: '';
    display: block;
    width: 10px;
    height: 15px;
    background-image: url('../images/btn-white-arrow-right.png');
    position: absolute;
    right: 12px;
    top: 10px;
}

通过使用:after选择器,我使用CSS添加了一个元素来包含这个小图标。您可以通过在a元素中添加span或<i>元素来实现同样的目的。但我认为这是一种向按钮添加图标的更简洁的方式,而且它是跨浏览器支持的。

你可以在这里查看小提琴: http://codepen.io/anon/pen/PNzYzZ

过时的答案:它现在在主要浏览器中实现,请参阅 这个问题还有其他答案。

CSS3修改了背景位置的规格,使它可以在不同的原点上工作。不幸的是,我找不到任何证据表明它已经在任何主流浏览器中实现。

http://www.w3.org/TR/css3-background/#the-background-position 参见例12。

background-position: right 3em bottom 10px;

如果你有一个固定宽度的元素,并且知道你的背景图像的宽度,你可以简单地设置background-position为:元素的宽度-图像的宽度-你想要在右边的间隙。

例如:对于一个100px宽的元素和一个300px宽的图像,要在右侧获得10px的间隙,您将其设置为100-300-10=-210px:

#myElement {
  background:url(my_image.jpg) no-repeat -210px top;
  width:100px;
}

你在元素的左边得到了图像最右边的80像素,在右边有一个20px的间隙。

我知道这听起来很愚蠢,但有时它节省了时间……我用垂直的方式(在底部的差距)导航链接与文字下面的图像。

但不确定这适用于你的案子。

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

你有一个名为#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;
}

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

这将适用于大多数现代浏览器…除了IE(浏览器支持)。尽管该页面列出了支持>= IE9,但我的测试并不同意这一点。

你可以像这样使用calc() css3属性;

.class_name {
    background-position: calc(100% - 10px) 50%;
}

对我来说,这是最干净、最合乎逻辑的方式来实现向右的边缘。我还使用了border-right: 10px solid transparent;IE。