[英]background-image css does not show in img tag
我的bootstrap html中的响应式图像没有显示:
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<img class="myimg img-responsive"/>
</div>
</div>
</div>
CSS
.myimg {
background-image: url("http://images.wikia.com/worldlanguages/images/6/63/Wikipedia-logo.png");
display:block;
height:100%;
width:100%;
}
<img src="...">
会起作用,但我需要在css中定义图像。
这个类似的线程建议使用<div>
并删除url()
的引号,但这没有帮助。
为什么不显示?
你需要为所有父母设置身高,你需要background-size: cover
( 演示 )
html, body {
height: 100%;
}
.container {
height: 100%;
}
.row,
.col-sm-12 {
height: 100%;
}
.myimg {
background-image: url("//lorempixel.com/200/200");
background-size: cover;
display: block;
height:100%;
width:100%;
}
.myimg2 {
background-image: url("//lorempixel.com/200/200");
background-size: cover;
display: block;
height:100%;
width:100%;
}
.myimg3 {
background-image: url("//lorempixel.com/200/200");
background-size: cover;
display: block;
height:100%;
width:100%;
}
如果您想要响应性地更改背景图像,您可以这样做。
( 演示 )
html, body {
height: 100%;
}
.container {
height: 100%;
}
.row,
.col-sm-12 {
height: 100%;
}
.myimg, .myimg2, .myimg3 {
background-size: cover;
display: block;
height:100%;
width:100%;
}
@media (max-width: 500px) {
.myimg {
background-image: url("//lorempixel.com/500/500/cats");
}
.myimg2 {
background-image: url("//lorempixel.com/500/500/business");
}
.myimg3 {
background-image: url("//lorempixel.com/500/500/transportation");
}
}
@media (max-width: 750px) {
.myimg, .myimg2, .myimg3 {
.myimg {
background-image: url("//lorempixel.com/750/750/cats");
}
.myimg2 {
background-image: url("//lorempixel.com/750/750/business");
}
.myimg3 {
background-image: url("//lorempixel.com/750/750/transportation");
}
}
}
@media (max-width: 1000px) {
.myimg {
background-image: url("//lorempixel.com/1000/1000/cats");
}
.myimg2 {
background-image: url("//lorempixel.com/1000/1000/business");
}
.myimg3 {
background-image: url("//lorempixel.com/1000/1000/transportation");
}
}
您无法通过css设置图像src。 你必须把img变成一个块并设置适当的宽度/高度来显示背景。 然而,这对我来说听起来并不奇怪。 你应该在div上做:
<div class="myimg">
</div>
.myimg {
width: 100px; // change to your background width
height: 100px // change to your background height
background: url('path/to/img');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.