2

See my codes on jsFiddle: http://jsfiddle.net/dpMss

HTML codes:

<div>
    <img src="http://www.google.com.hk/intl/zh-CN/images/logo_cn.png" width="276" height="110" alt="Google China">
</div>​

CSS codes:

div {
    height: 118px;
    line-height: 118px;
    background: red;
}
img {
    vertical-align: middle;
}​

1, Why my image can't be displayed vertical center in ?

2, How to let my image be displayed in vertical center in via line-height and vertical-align CSS properties?

Thank you!

weilou
  • 4,419
  • 10
  • 43
  • 56
  • 1
    The reason it does not work is because the image is an `inline` element and will sit of the same line as text. Because of that there is extra padding under the image to accomodate letters that take space below the text line - such as p, q etc - so the image does not appear vertically aligned. Try hovering over the image using Firebug and you will see the extra spacing below. – My Head Hurts Feb 16 '12 at 10:30
  • 1
    [This Stack Overflow answer](http://stackoverflow.com/questions/5804256/why-an-image-inside-a-div-has-an-extra-space-below-the-image) explains it better than I do. – My Head Hurts Feb 16 '12 at 10:36

2 Answers2

2

try this:

div {
  height: 300px;
  background: red;
}
div img {
  position:relative;
  top:50%;
  margin-top:-55px;
}

-55px aligns your picture to the real center, it's the half of image's height. It works for me in Chrome and Firefox. http://jsfiddle.net/b24UH/

wobmene
  • 1,108
  • 9
  • 14
1

Write like this:

div {
    height: 200px;
    line-height: 118px;
    background: red;
    display:table-cell;
    vertical-align: middle;
    width:100%;
}
img {
    vertical-align: middle;
}

UPDATED

write like this:

div {
    height: 200px;
    line-height: 200px;
    background: red;
    vertical-align: middle;
    width:100%;
}
img {
    vertical-align: middle;
}

http://jsfiddle.net/dpMss/10/

It's work in all browsers


sandeep
  • 91,313
  • 23
  • 137
  • 155
  • now +1 because i haven't seen the trick with line-height before – mkk Feb 16 '12 at 10:53
  • 1
    This doesn't work. All you have done is changed `div` and `line-height` to `200px`. Change their heights back to `118px` and you have exactly the same problem as before: http://jsfiddle.net/dpMss/13/. – My Head Hurts Feb 16 '12 at 11:06
  • i just noticed vertical-align property and haven't paid much attention to anything else because many people are confused why it is not working - so far i thought it is only working in td – mkk Feb 16 '12 at 11:20