Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Why "vertical-align: middle" does not work?

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:

enter image description here

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.

like image 709
Misha Moroshko Avatar asked Jul 19 '11 06:07

Misha Moroshko


People also ask

How do I align text in the middle vertically CSS?

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.

How do I center something vertically in CSS?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How does vertical-align middle work?

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.

Why is text-align center not working?

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.


1 Answers

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/

like image 131
sandeep Avatar answered Oct 11 '22 06:10

sandeep