我需要动态调整 div 的高度以显示其背景图像。我正在努力让它工作,这样我就可以使用 CSS 变换技巧,将鼠标悬停在 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>
最佳答案
使用 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>
关于javascript - 根据背景图像调整 div 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37369294/