Steve
Steve

Reputation: 2217

*Perfect* vertical image alignment

I have a square div of fixed size and wish to place an arbitrary size image inside so that it is centred both horizontally and vertically, using CSS. Horizontally is easy:

.container { text-align: center }

For the vertical, the common solution is:

.container {
    height: 50px;
    line-height: 50px;
}
img {
    vertical-align: middle;
}

But this is not perfect, depending on the font size, the image will be around 2-4px too far down.

To my understanding, this is because the "middle" used for vertical-align is not really the middle, but a particular position on the font that is close to the middle. A (slightly hacky) workaround would be:

container {
    font-size: 0;
}

and this works in Chrome and IE7, but not IE8. We are hoping to make all font lines the same point, in the middle, but it seems to be hit-and-miss depending on the browser and, probably, the font used.

The only solution I can think of is to hack the line-height, making it slightly shorter, to make the image appear in the right location, but it seems extremely fragile. Is there a better solution?

See a demo of all three solutions here: http://jsfiddle.net/usvrj/3/

Those without IE8 may find this screenshot useful:

IE8 screenshot when font-size is set to 0

Upvotes: 13

Views: 1426

Answers (5)

Danield
Danield

Reputation: 125641

If css3 is an option, then flexbox does a good job at vertical and horizontal aligning:

UPDATED FIDDLE

.container {
    display:flex;
    align-items: center; /* align vertical */
    justify-content: center; /* align horizontal */
}

Upvotes: 3

pixlboy
pixlboy

Reputation: 1502

Here is a small JS Fiddle I have made: http://jsfiddle.net/rachit5/Ge4YH/

I believe it matches your requirement.

HTML:

<div>
    <img src=""/>
</div>

CSS:

div{height:400px;width:400px;position:relative;border:1px solid #000;}
img{position:absolute;top:0;left:0;right:0;bottom:0;margin:auto;}

Upvotes: 0

Arthur K
Arthur K

Reputation: 74

How about using your image as a background? This way you could center it consistently everywhere. Something along these lines:

margin:5px;
padding:0;
background:url(http://dummyimage.com/50) no-repeat center center red;
height:60px;
width:60px;

Upvotes: 2

Shauno
Shauno

Reputation: 1258

This is REALLY hacky, but it is what we used to do in the ie6 days.

.container {
     position: relative;
}
img {
     position: absolute;
     top: 50%;
     left: 50%;
     margin-top: -12px; // half of whatever the image's height is, assuming 24px
     margin-left: -12px; // half of whatever the image's width is, assuming 24px
}

I may be missing something in this example, but you get the idea.

Upvotes: 1

Mateusz Hajdziony
Mateusz Hajdziony

Reputation: 109

Have you tried the following:

img {
    display: block;
    line-height: 0;
}

I usually use this hack, but I haven't really checked it that thoroughly in IE8.

Upvotes: 0

Related Questions