据我所知,不可能从任何块的右边框放置CSS背景图像1em,也不可能从底部放置图像1em.
以下代码从左侧放置背景图像1em,从顶部放置2em.
<div class="foo" style="background: url('bar.png') no-repeat 1em 2em">
  Some text here
</div>
如果框的大小是动态的并且假设您无法更改HTML,那么在CSS中是否有任何方式指定背景图像应该"远离右边缘"?
(百分比不起作用,因为盒子可以改变大小)
如果无法做到这一点,那么您需要对HTML进行的最小更改量是多少?
这是我提出的解决方法:
<style>
div.background
{
  float: right; 
  background: url('bar.png') no-repeat top left; 
  margin-right: 1em; 
  width: 16px; 
  height: 16px;
}
</style>
<div class="foo">
  <div class="background" style=""> </div>
  Some text here
</div>
Vla*_*lin 27
在CSS3背景位置规范允许您将锚点从左上角变成你想要的任何东西.例如,以下内容将从右侧设置图像1em的下角,从底部设置2px:
background-position: right 1em bottom 2px;
确认工作于:
IE9/10,Firefox 13 +,Chrome 26 +,Opera 11 +,Seamonkey 2.14 +,Lunascape 6.8.0
截至2013年4月,只有IE6-8和一些边缘浏览器缺乏支持.
这是一个测试页面:http://jsbin.com/osojuz/1/edit
经过一些研究,背景位置的实际 x 像素长度始终从元素的左侧开始计算。实现此目的的唯一方法(不使用其他元素)是使用 javascript,计算给定元素宽度的左侧长度:
var rightMargin = "10"; // in pixels
var imageWidth = "16";
var left = element.style.clientWidth - imageWidth - rightMargin;
element.style.backgroundPosition = "0px " + left + "px";