简体   繁体   English

具有动态高度的CSS div,可响应背景图像

[英]CSS div with dynamic height to responsive background image

I trying to create a class with a dynamic image background on bootstrap3 without success. 我试图在bootstrap3上创建一个具有动态图像背景的类,但没有成功。 Instead use height equal to 180px i trying to use 100% to make it responsive. 而是使用等于180px的高度,我尝试使用100%使其具有响应性。 Whats wrong? 怎么了?

 .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> 

set your background-size to cover and specify a min-height . background-size设置为cover并指定min-height

check out the fiddle 查看小提琴

there are a few ways to make an image responsive, but there are questions, do you want to keep the aspect ratio? 有几种方法可以使图像响应,但是有一些问题,您是否要保持宽高比?

if you want to keep your approach of using a div and assigning background properties you can use the following css: 如果要保留使用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%;
}

this will make the div 100% height and width of the parent, but the image background-size is 100% width with auto height. 这将使div的父级高度和宽度为100%,但是图像背景尺寸为100%宽度,且具有自动高度。 This means, the height will keep its aspect ratio of the original image. 这意味着,高度将保持其原始图像的纵横比。

if you want the image to take the full height-width of the parent and not maintain its aspect ratio you can change background-size to: 如果您希望图像占据父对象的整个高度-宽度而不保持其宽高比,则可以将背景大小更改为:

background-size: 100% 100%;

you can play around with it here http://jsfiddle.net/1f36wedc/ 您可以在这里尝试一下http://jsfiddle.net/1f36wedc/

The responsive idea for images is like this: 图像的响应想法是这样的:

<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%;  
}

Hope this help 希望有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM