Abraham
Abraham

Reputation: 20686

CSS vertical-align slightly off

OK, so this is driving me nuts: http://jsfiddle.net/C3YMJ/2/
The images is supposed to be vertically centered in the div, but as you can see, it's slightly off-center. I can't get it to center exactly. Any help would be much appreciated.
Thanks.

Upvotes: 2

Views: 1870

Answers (5)

JSW189
JSW189

Reputation: 6325

You can use the CSS position attribute to vertically center your image:

div { 
    position:relative;
}

img {
    position:absolute;
    top:0;
    bottom:0;
    margin:auto;
}

JS Fiddle: http://jsfiddle.net/C3YMJ/22/

Upvotes: 4

ckornell
ckornell

Reputation: 13

I would take the height off the div and use padding on the top and bottom instead.

html: <div><img src="https://www.google.com/images/srpr/logo3w.png" height="10" /></div>​
css:  div {background-color: blue; padding: 5px 0;}

That will make it align in the middle.

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

Adding line-height: 100% to your DIV will solve the problem.

Demo: http://jsfiddle.net/C3YMJ/9/

Upvotes: 1

Wouter J
Wouter J

Reputation: 41934

Your code doesn't work. If you increase both heights it is totally not centered: http://jsfiddle.net/WouterJ/C3YMJ/3/

See the Centering in the unkown article from Chris Coyier for more information about how to solve this.

EDIT: Remove wrong statement.

Upvotes: -1

Guffa
Guffa

Reputation: 700232

You can remove the vertical-align property, it has no effect as the image has no child elements that it could apply to.

Use line-height: 20px; on the div.

Upvotes: 1

Related Questions