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.
Use the CSS line-height property Add the line-height property to the element containing a text larger than its font size. By default, equal spaces will be added above and below the text, and you'll get a vertically centered text.
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
The vertical-align property in CSS controls how elements set next to each other on a line are lined up. In order for this to work, the elements need to be set along a baseline. As in, inline (e.g. <span> , <img> ) or inline-block (e.g. as set by the display property) elements.
Note, however, that text-align:center doesn't always work. This grey aside block is not centre-aligned. This is because text-align:center only affects inline elements, and <aside> is not an inline element by default. It is a block-level element.
You can use position:absolute;
for this.
For example:
a {
display: block;
background: #000;
line-height: 40px;
height:80px;
position:relative;
}
img {
position:absolute;
top:50%;
margin-top:-16px;
}
NOTE: This gives margin-top
half of the image size.
Check this http://jsfiddle.net/cXUnT/7/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With