Reputation: 20440
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.
Upvotes: 5
Views: 57230
Reputation: 1
Give id to your like then in your css →
#foto{
margin-left:180px;
}
Upvotes: 0
Reputation: 6043
EDIT: re-reading, you want the image size to be fixed.
div.cnt {
margin-left: auto;
margin-right: auto;
text-align: center;
display: table-cell;
vertical-align: middle;
min-height: 150px;
min-width: 150px;
}
Upvotes: 1
Reputation: 32767
If the ctn
has to be a fixed sized (ex: 150x150) and the image has to be proporcional and not bigger than that div, this is a 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 way will center the div in the middle of the screen and the image will not be bigger than 150x150 but it will mantain its proporcionality.
Upvotes: 0
Reputation: 6274
i think this is your answer
.container img { width: 100%;}
.container {display: table-cell;vertical-align: middle}
it fits, in the center of your fixed size div, and image proportions are not changed.
Upvotes: 2
Reputation: 8771
The easiest way should be :
div.cnt {
width: 150px;
height: 150px;
}
<div class="ctn" style="background: url('some-img.jpg') 50% 50% no-repeat;">
</div>
Upvotes: 0
Reputation: 14575
Try the following:
text-align: center;
display: table-cell;
vertical-align: middle;
Upvotes: 5
Reputation: 827
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
Upvotes: 15
Reputation: 1356
set style="margin-let:auto; margin:right:auto"
also specify width to the image else it will not work
Upvotes: -4