jon.s jon.s - 6 months ago 21
CSS Question

Size a div based on a background image

I need to dynamically size a div's height in order to show its background image. I'm trying to get this working so I can do that CSS transform trick where you mouse over a div and the background enlarges, but my images will be of various sizes. Any help is appreciated... I'm stuck!

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>

Answer

The way to do this by using the img tag, not background-image

You need to wrap each image in a div. Set the div to overflow:hidden. Width of image must be 100%; Scale the img using transform:scale(x); Set the width of image using the div's width.

Here's a demo

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

Comments