How to create image center in div?
My HTML code looks like this:
<div class="ctn"> <img src="some-img.jpg"/> </div> ctn should be a fixed size, e.g. 150 * 150.
But the IMG size can be larger or smaller: 200 * 50, 50 * 200, 50 * 50, etc.
How to make the image fit in the center of the div ? The proportion of the image should not be changed.
==== ==== UPDATE Yes, I need both a chori and a vertical center.
You can 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
If ctn should be a fixed size (for example: 150x150) and the image should be proportional and no larger than a div, this is the solution:
CSS
.ctn{ background-color:#F00; margin-left:auto; margin-right:auto; position:relative; overflow:hidden; height:150px; width:150px; } .ctn div{ display:table-cell; vertical-align: middle; text-align:center; } .ctn div img{ width:150px; } HTML
<div class="ctn"> <div> <img src="url" /> </div> </div> This method will center the div in the middle of the screen and the image will not be larger than 150x150, but it will maintain its proportionality.
ctn should be a fixed siz...">