2016-05-22 193 views
1

我需要动态调整div的高度以显示其背景图像。我试图让这个工作,所以我可以做的CSS转换技巧,你把鼠标放在一个div和背景放大,但我的图像将有不同的大小。任何帮助表示赞赏...我卡住了!根据背景图像尺寸div

CSS:

<style> 
.dynaimage{ 
    width:80%; 
    background-image:url('variable-image'); 
    background-size:100%; margin:0 auto; 
} 

</style> 

HTML:

<div class="dynaimage"></div> 
<p>The above div should take the height of its background image</p> 

回答

1

使用img标签做到这一点的方式,而不是background-image

你需要在一个div包裹每幅图像。将div设置为overflow:hidden。图像宽度必须为100%;使用transform:scale(x)来缩放img;使用div的宽度设置图像的宽度。

这里有一个演示

.img-wrap { 
 
    overflow: hidden; 
 
    display: inline-block; 
 
    /*width: 20%;*/ 
 
} 
 
.img-wrap img { 
 
    width: 100%; 
 
    -webkit-transition: 1s; 
 
    -moz-transition: 1s; 
 
    -ms-transition: 1s; 
 
    -o-transition: 1s; 
 
    transition: 1s; 
 
} 
 
.img-wrap:hover img { 
 
    transform: scale(1.2); 
 
}
<!-- Image size: 420 x 220 --> 
 
<div class="img-wrap"> 
 
    <img src="http://lorempixel.com/image_output/animals-q-c-420-220-3.jpg" alt=""> 
 
</div> 
 

 
<!-- Image size: 200 x 290 --> 
 
<div class="img-wrap"> 
 
    <img src="http://lorempixel.com/image_output/animals-h-c-200-280-2.jpg" alt=""> 
 
</div>

+0

这比结我的大脑周围捆绑的方式更容易!日Thnx! –