Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a image center in a div?

Tags:

html

css

My HTML code looks like this:

<div class="ctn">
    <img src="some-img.jpg"/>
</div>

The ctn should be a fixed size, say, 150*150.

But the size of IMGs may bigger or smaller: 200*50, 50*200, 50*50 etc.

How do i make the image fit in the center of the div ? The image's proportion should not be changed.

====UPDATE==== Yes, I need both hori & vertical center.

like image 446
WoooHaaaa Avatar asked Nov 30 '22 21:11

WoooHaaaa


2 Answers

You could add css, to center the image both horizontally and vertically:

DIV.ctn {
    min-height: 150px;
    min-width: 150px;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
    display: table-cell;
    vertical-align: middle }

...

<div class="ctn">
    <img src="some-img.jpg"/>
</div>

Edit: for details see: http://www.w3.org/Style/Examples/007/center.html

like image 111
noamik Avatar answered Dec 03 '22 11:12

noamik


Try the following:

text-align: center;    
display: table-cell;
vertical-align: middle; 

DEMO

like image 38
Andy Avatar answered Dec 03 '22 09:12

Andy