Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize to fit image in div, and center horizontally and vertically

Tags:

css

image

center

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.

like image 808
Benjamin Crouzier Avatar asked Jun 26 '13 12:06

Benjamin Crouzier


People also ask

How do I autofit an image in a div?

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.

How do I center a vertically and horizontally div?

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.

How do I fit a div image without stretching it?

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.


2 Answers

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; } 
like image 58
Benjamin Crouzier Avatar answered Oct 07 '22 18:10

Benjamin Crouzier


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> 
like image 40
Hugo Avatar answered Oct 07 '22 19:10

Hugo