具有动态高度到响应式背景图像的CSS div

时间:2015-07-21 20:24:34

标签: html css image dynamic

我尝试在bootstrap3上创建一个具有动态图像背景的类,但没有成功。而是使用高度等于180px我尝试使用100%使其响应。怎么了?

.audio-cover {
	background: url("http://media.merchantcircle.com/22662073/180px-Smiley_svg_full.png");
	background-size: contain;
	background-repeat: no-repeat;
	height: 100%; //instead use 180px
}
<div class="col-xs-4 col-sm-4 col-md-4 audio-cover"></div>

3 个答案:

答案 0 :(得分:2)

background-size设置为cover并指定min-height

查看fiddle

答案 1 :(得分:1)

有几种方法可以使图像响应,但有问题,你想保持宽高比吗?

如果你想保持使用div的方法并分配背景属性,你可以使用以下css:

#image {
    background-image: url(http://www.ucl.ac.uk/news/news-articles/1213/muscle-fibres-heart.jpg);
    background-size: 100% auto;
    background-repeat: no-repeat;
    width: 100%;
    height: 100%;
}

这将使div成为父级的100%高度和宽度,但图像背景大小为100%宽度和自动高度。这意味着,高度将保持原始图像的纵横比。

如果您希望图像采用父级的完整高度宽度而不保持其宽高比,则可以将背景大小更改为:

background-size: 100% 100%;

你可以在这里玩http://jsfiddle.net/1f36wedc/

答案 2 :(得分:0)

图像的响应性想法是这样的:

<div>
    <img src="SOME_WHERE" />
</div>

div{
    width: X; // depended on your logic
    height: 170px;
    overflow: hidden; // by this one, maybe you lost some part of image, but is okay
}
div > img{
    max-width: 100%;  
}

希望这个帮助