Jaroslav Klimčík
Jaroslav Klimčík

Reputation: 4828

Image vertical align middle fix code

I want to fit image into vertical align but I still can't solve this. I have this code which does not work properly:

CSS:

#bigpic {
    width: 248px;
    height: 315px;
    float: left;
    margin: 0 0 30px 0;
    text-align: center;
}

.helper {
    float: left;
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

#bigpic img {
    vertical-align: middle;
    max-width: 248px;
    max-height: 315px;
}

HTML:

<div id="bigpic">
    <span class="helper"></span>
    <img src="http://lorempixel.com/100/200" />
</div>

I just don't see any problem why doesn't it work. Jsfiddle here http://jsfiddle.net/3X7rg/. Answer into jsfiddle would be the best. Thanks advance.

Upvotes: 0

Views: 301

Answers (3)

AnaMaria
AnaMaria

Reputation: 3621

Here is another way to do it. I prefer this method because it allows variable height of the div as well as image. So i don't have to manually set the height.

WORKING DEMO

This is achieved using table-cell & vertical-align attributes in CSS

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

Upvotes: 0

David
David

Reputation: 1889

add line-height: 315px demo : http://jsfiddle.net/3X7rg/2/

#bigpic {
    width: 248px;
    height: 315px;
    float: left;
    margin: 0 0 30px 0;
    text-align: center;
    border: 1px solid black;
    line-height: 315px; /*must equal must be equal to height of the div*/
}

Upvotes: 1

Erwin van Ekeren
Erwin van Ekeren

Reputation: 730

You can play with your position and percentage. http://jsfiddle.net/3X7rg/10/

#bigpic {
position: absolute;
float: left;
left: 200px;
width: 248px;
height: 315px;
border: 1px solid black;
}

#bigpic img {
position: absolute;
width: 100px;
height: 200px;
left: 50%;
top: 50%;
margin: -100px 0 0 -50px;
}

Upvotes: 1

Related Questions