Consider the following example: (live demo here)
HTML:
<a><img src="http://img.brothersoft.com/icon/softimage/s/smiley.s_challenge-131939.jpeg" /></a>
CSS:
a {
display: block;
background: #000;
line-height: 40px;
}
img {
vertical-align: middle;
}
The output is:
Why the image is not vertically centered ?
How could I fix that so it will work in all major browsers ?
Please don't assume any image size (like 32x32 in this case), because in the real case the image size is unknown.
If you know the vertical size of the element and the line height, then you can vertically center it by using
vertical-align: top
plus a top margin.For illustration, I created: http://jsfiddle.net/feklee/cXUnT/30/
Not sure what's the cause.
Removing the
line-height
and addingmargins
to the image does the trick.I had the same problem. This works for me:
Just put the img tag inside a div tag the set display:table-cell vertical-align: middle to the div. Parent tag should be display:table
Example:
Css
HTML
You should have
display: table-cell
I think, this works only in tables.. I useline-height
equal to height of the element and it works too.Try using a background image on an
<a>
: