Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*Perfect* vertical image alignment

Tags:

css

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

like image 423
Steve Avatar asked May 08 '12 14:05

Steve


2 Answers

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;
like image 173
Arthur K Avatar answered Oct 26 '22 11:10

Arthur K


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 */
}
like image 20
Danield Avatar answered Oct 26 '22 12:10

Danield