Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vertical align center image in fixed size div

Tags:

I have a div which is 145px X 145px. I have an img inside this dive. The img could be of any size (longest side being 130px). I would like the image to be centered vertically in the div. Everything that I have tried works in most browsers, but not IE7. I need something that will work in IE7.

like image 981
David Avatar asked Feb 15 '11 15:02

David


People also ask

How do I center an image in a fixed div?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.

How do I vertically align an image in HTML?

Answer: Use the CSS vertical-align Property You can align an image vertically center inside a <div> by using the CSS vertical-align property in combination with the display: table-cell; on the containing div element.

How do I center align an image in CSS?

To center an image, we have to set the value of margin-left and margin-right to auto and make it a block element by using the display: block; property. If the image is in the div element, then we can use the text-align: center; property for aligning the image to center in the div.


2 Answers

here's a cross-browser solution:

<div class="img-container"><img src="picture.png" class="cropped"/></div>   div.img-container {      width: 390px;      height: 211px;      position: relative;      margin-left: auto;      margin-right: auto;      overflow: hidden;  } img.cropped {     position: absolute;     margin: auto;     top: 0;     left: 0;     right: 0;     bottom: 0; } 
like image 162
ndrizza Avatar answered Oct 01 '22 16:10

ndrizza


You can replace the image by a background on the div like this :

<div style="background:url(myimage.jpg) no-repeat center center"></div> 
like image 32
A.Baudouin Avatar answered Oct 01 '22 15:10

A.Baudouin