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)
Joh*_*ish 52
这实际上很容易完成.你几乎就在那里,做你做过的事background-position: right center;.在这种情况下实际需要的是非常类似的东西.我们将这些转化为百分比.我们知道center= 50%,所以这很容易.现在,为了获得你想要的填充,你需要像这样定位背景:background-position: 99% 50%.
第二种也是更有效的方法是使用相同的background-position想法,然后使用background-position: 400px (width of parent) 50%;.当然,这种方法需要静态宽度,但每次都会给你同样的东西.
小智 10
实际上有一个原生解决方案,使用四值到背景位置
.CssClass {background-position: right 10px top 20px;}
这意味着右边10px,顶部20px.你也可以使用三个值,第四个值将被计为0.
小智 7
你可以使用background-origin:padding-box; 然后在你想要的地方添加一些填充,例如:#logo {background-image: url(your/image.jpg); background-origin:padding-box; padding-left: 15%;}
这样你就可以将图像附加到包含它的div填充框中,这样你就可以将它放在任何你想要的位置.
如果其他人需要为具有background-image和background-size: contains或cover的内容添加填充,我使用了以下方法,这是一个很好的方法。您可以用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)
这意味着您不必定义宽度。