jon.s jon.s - 4 months ago 8x
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!


background-size:100%; margin:0 auto;



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


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="" alt="">

<!-- Image size: 200 x 290 -->
<div class="img-wrap">
  <img src="" alt="">