定位背景图片,添加填充

Ian*_*vis 57 css background-image

我想为div添加一个背景,右侧居中,但是!对图像有一些填充.div有文本的填充,所以我想稍微缩进背景.可能最有意义的例子:

http://jsbin.com/umuvud/edit#javascript,html,live

谢谢!

Jos*_*kle 85

更新答案:

多次评论说这不是这个问题的正确答案,我同意.回到这个答案时,IE 9仍然是新的(大约8个月),包括我自己在内的许多开发人员都需要<= IE 9的解决方案.IE 9是IE 开始支持的时候background-origin.然而,它已经超过六年半了,所以这里是我强烈建议使用实际边框的更新解决方案.如果需要<IE 9支持.我的原始答案可以在演示片段下面找到.它使用不透明边框来模拟背景图像的填充.

#hello {
  padding-right: 10px;
  background-color:green;
  background: url("https://placehold.it/15/5C5/FFF") no-repeat scroll right center #e8e8e8;
  background-origin: content-box;
}
Run Code Online (Sandbox Code Playgroud)
<p id="hello">I want the background icon to have padding to it too!I want the background icon twant the background icon to have padding to it too!I want the background icon to have padding to it too!I want the background icon to have padding to it too!</p>
Run Code Online (Sandbox Code Playgroud)

原答案:

你可以使用与背景颜色相同的10px边框来伪造它:

http://jsbin.com/eparad/edit#javascript,html,live

#hello {
   border: 10px solid #e8e8e8;
   background-color: green;
   background: url("http://www.costascuisine.com/images/buttons/collapseIcon.gif")
               no-repeat scroll right center #e8e8e8;
}
Run Code Online (Sandbox Code Playgroud)

  • 另一种方法,在CSS中使用calc方法.background-position-x:calc(100% - 4px); (16认同)
  • 或者使用background-origin属性https://developer.mozilla.org/en-US/docs/Web/CSS/background-origin,它旨在解决类似这样的问题.IE9及以上支持:http://jsbin.com/umuvud/50/edit (8认同)
  • 我很喜欢这个答案!感觉很讨厌,但我赞成 (3认同)
  • 真棒!你甚至可以使用透明边框,如果你使用ems作为边框宽度,这对响应度很有用.在我看来,根本不是很狡猾,非常聪明! (3认同)

Joh*_*ish 52

这实际上很容易完成.你几乎就在那里,做你做过的事background-position: right center;.在这种情况下实际需要的是非常类似的东西.我们将这些转化为百分比.我们知道center= 50%,所以这很容易.现在,为了获得你想要的填充,你需要像这样定位背景:background-position: 99% 50%.

第二种也是更有效的方法是使用相同的background-position想法,然后使用background-position: 400px (width of parent) 50%;.当然,这种方法需要静态宽度,但每次都会给你同样的东西.

方法1(99%50%)
方法2(400px 50%)

  • background-position:99%50%是我正在寻找的.谢谢. (2认同)
  • 这是正确的答案.谢谢. (2认同)

小智 10

实际上有一个原生解决方案,使用四值到背景位置

.CssClass {background-position: right 10px top 20px;}

这意味着右边10px,顶部20px.你也可以使用三个值,第四个值将被计为0.

  • 不知道为什么他们将黑客标记为正确的答案!这是正确的方法. (2认同)
  • 如果您还尝试使用 background-size: cover,则接受的答案会更好,因为它可以正确控制图像的大小。对于此解决方案,您还必须定义图像的大小以在右侧(和底部)获得正确的填充。 (2认同)

小智 7

你可以使用background-origin:padding-box; 然后在你想要的地方添加一些填充,例如:#logo {background-image: url(your/image.jpg); background-origin:padding-box; padding-left: 15%;} 这样你就可以将图像附加到包含它的div填充框中,这样你就可以将它放在任何你想要的位置.


JHa*_*air 5

如果其他人需要为具有background-imagebackground-size: containscover的内容添加填充,我使用了以下方法,这是一个很好的方法。您可以用10%2vw或任何您喜欢的值替换边框宽度。

.bg-image {
    background: url("/image/logo.png") no-repeat center #ffffff / contain;
    border: inset 10px transparent;
    box-sizing: border-box;
}
Run Code Online (Sandbox Code Playgroud)

这意味着您不必定义宽度。