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

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

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

当前回答

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

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

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

其他回答

!! 过时的答案,因为CSS3带来了这个功能

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

不。

流行的变通方法包括

改为在元素上设置右边距 为图像本身添加透明像素,并将其定位在右上方 或者在元素宽度已知后使用jQuery计算位置。

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

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

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

我的问题是,当窗口调整大小时,我需要背景图像与右侧边界保持相同的距离,例如平板电脑/手机等 我的解决方案是像这样使用一个百分比:

background-position: 98% 6px;

它会固定在原地。

一个简单但肮脏的技巧是简单地添加你想要作为背景的图像的偏移量。它是不可维护的,但它可以完成工作。

正如这里提出的,这是一个非常完美的跨浏览器解决方案:

background: url('/img.png') no-repeat right center;
border-right: 10px solid transparent;

我之所以使用它,是因为浏览器还不太支持CSS3的特性,即在标记为解决问题的答案中指定偏移量。如。