I have an image in a div. I would like the image to resize to fit the div, and be horizontally and vertically centered. I would like a solution that works in ie >= 8.
To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.
You can do this by setting the display property to “flex.” Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
Those images on the site you linked to are actual size, so the simple answer is just to resize the image. You can't really do this without "stretching" the image if the image happens to be less than 300px wide or tall, but you can do it without changing the ratio, which is what I think you mean.
This is one way to do it:
Fiddle here: http://jsfiddle.net/4Mvan/1/
HTML:
<div class='container'> <a href='#'> <img class='resize_fit_center' src='http://i.imgur.com/H9lpVkZ.jpg' /> </a> </div>
CSS:
.container { margin: 10px; width: 115px; height: 115px; line-height: 115px; text-align: center; border: 1px solid red; } .resize_fit_center { max-width:100%; max-height:100%; vertical-align: middle; }
Only tested in Chrome 44.
Example: http://codepen.io/hugovk/pen/OVqBoq
HTML:
<div> <img src="http://lorempixel.com/1600/900/"> </div>
CSS:
<style type="text/css"> img { position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); max-width: 100%; max-height: 100%; } </style>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With