March 24, 2012

How can I center an image of *unknown size* in a div, both vertically and horizontally?

Question by alexx0186

I am looking to handle files that were uploaded by users. The main issue in that situation is that they differ in size.

How can I center an image of unknown size, both vertically and horizontally, into a div?

Thanks a lot

EDIT: I am making a thumbnail for an image. Basically, I want to keep the div to the same size, and I want the image inside that div to fit the div, but without changing the scale. I am using overflow:hidden

EDIT:My code is

<div class='pic'><img id='theimage' src='image.png'></div>

and my CSS is

#theimage {
    vertical-align: middle;
    display: inline;

}

Answer by Starx

Force the container to behave as a table cell.

#container {
     display: table-cell; 
     vertical-align: middle; 
     text-align: center;
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!