Search code examples
cssimageoverflowcenterhidden

How can I center an <img> inside a div and have it scale with the div's height?


I'm using centered imgs to act as backgrounds for some tiles. I'm trying to have these images scale with their parent div's height and if they are wider then their parent's for them to hide the overflow.

Example:

* I've got it working now. Answers are below, I'm updating this code to display all I needed to use to get it to work *

HTML

<div class="container">
    <img class="derp" src="http://gridiculo.us/images/kitty02.jpg">
</div>

CSS:

.container {
    height:250px;
    width:50%;
}
.derp{
  object-fit: cover;
  height: 100%;
  width: 100%;
}

Here's a near-example: http://codepen.io/chriscoyier/pen/myPMGB

The difference would be that I'm using s and not background-image, and that instead of the img filling the div completely it would fit to the height and hide the width overflow.

I'm trying to avoid using background-image since I'm using a lot of these tiles and making CSS rules for every one isn't going to work.


Solution

  • In order to scale it with the div's height, I'd change the height from px to % - this way, the larger's the div, the larger's the picture. In order to certain the image, i'd use margin in the image css. That'd look like so:

        .derp{
            height:80%;
            width:80%;
            margin:10%;
         }
    .container {
        height:250px;
        width:50%; /* needed */
        /* inner img is centered horizontally */
        vertical-align:top;
        text-align:center;
        overflow-x:hidden;
    }
    <div class="container" style="background-color:gray"> <!-- The background is there so you could see the image relative to the div -->
        <img class="derp" src="http://gridiculo.us/images/kitty02.jpg">
    </div>