CSS负的右背景位置

7
我知道可以通过如下方式在背景图片上设置负的左位置:
```css background-position: -10px 0; ```
这将会向左移动背景图像10像素。
#element {
    background: url(image.png) -20px 0 no-repeat;
}

这将使背景图片相对于 #element 左边缘向左偏移20像素,而不受 #element 宽度的影响。

但是是否有一种方法可以设置负的右侧位置,而无需给 #element 设置固定宽度(然后只需设置高正左值)?


换句话说,将图像定位在右侧边缘的左侧N像素?据我所知不可能。 - Jon
3个回答

20

这种效果无法通过简单的CSS实现是不正确的说法。您无需通过不必要的伪元素或多个div来使标记复杂化。

您可以在CSS中使用“calc”函数来让浏览器计算出容器宽度的100%,然后像这样添加负边距(请记得将负边距添加到100%而非减去它):

background-position: calc(100% + 20px) 0;

或者如果你更喜欢简写格式的标记:

background: url("image.png") calc(100% + 20px) 0 no-repeat;

这将使你的背景图片从其容器的左侧以100%的位置定位(从而获得与使用background-position:right相同的效果),并通过向其添加20px来获得您的负右边距。

您可以在此jsFiddle中查看该函数的演示:http://jsfiddle.net/58u665fe/

大多数主流浏览器都支持“calc”函数,尽管对于IE9<在某些情况下缺乏支持。您可以在http://caniuse.com/#feat=calc上了解更多关于哪些浏览器支持此功能的信息。


3
您想要做的事情并不能以您想要的方式实现。
解决方法可能是创建一个带有“position:relative;”属性的父div,然后在包含内容的div后面z-index另一个div。
<style>
    #parent {
        position: relative; 
    }
    #background {
        background: url(img.png) top left no-repeat;
        position: absolute;
        top: 0;
        left: -20px;
    }
    #content {
        position: absolute;
        top: 0;
        left: 0;
    }
</style>


<div id="parent">
    <div id="background"></div>
    <div id="content"></div>

这很聪明!但是你是不是指的是在#background中使用right: -20px而不是left: -20px - daGUY
这取决于您想要在哪里显示它。如果我按照问题所说的来做,实际上应该是 top: -20px; left: 0px;,因为第一个值是垂直位置,第二个值是水平位置。 - Plummer

2

有另一种方法可以在不改变标记的情况下实现这一点:

使用:after伪选择器,您可以向任何块的右侧添加图像,但这并不同于实际的CSS背景

所以您可以执行以下操作:

#element {
  position: relative;
}
#element:after{
  content: "";
  background: transparent url(image.png) 0 0 no-repeat;
  position: absolute;
  right: -20px;
  top: 0;
  height: 50px /*add height of your image here*/ 
  width: 50px /*add width of your image here*/
  z-index: 1;  
}
#element *{
  position: relative; 
  z-index: 2; /*this makes sure all the "background image" doesn't sit above the elements*/  
}

1
这个建议与这个类似,但我更喜欢后者(content: url(...); display:block;),因为它不需要指定“width”和“height”。 - dma_k

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接