0

I was try to vertically align an image inside div accurately. And i saw a solution that is add font-size : 0 to the container box.It did work, but also confuse me a lot.

I read some blog and 10.8 Line height calculations: the line-height and vertical-align properties,learn something like line box inline-level box Leading and half-leading.

but I still don't know how to use those conceptions to explain why the code snippet below can work right. Can someone explain the snippet step by step with the conceptions? Thank you!

* {
  margin : 0;
  padding : 0;
}
div {
  background-color: #000;
  line-height: 200px;
  font-size: 0;  /*what happened here*/
}
div img {
  vertical-align: middle;
}
<div>
  <img src="http://placehold.it/100x198/ffffff" alt="image">
</div>
Cabage
  • 337
  • 2
  • 11
  • Your code [seems to work](https://jsfiddle.net/5bz1rtfy/) even without the `font-size:0`. Can you demonstrate the problem you're having? – showdev Aug 12 '16 at 18:47
  • Must be different browser behaviours because I tried it on FF and chrome on mac and it works without the font size https://jsfiddle.net/mvju1k4r/ – Huangism Aug 12 '16 at 18:49
  • I set the div `line-height:200px` for div and `height:198px` for image to check is the image at the exactly center? Run the snippet you should see 1px black line on both top and under the image, but remove the `font-size:0`, it can't vertically align accurately. hope you can understand my broken english. – Cabage Aug 13 '16 at 02:15

2 Answers2

0

The CSS specification does not indicate how browsers should display text when the font-size is set to a value of zero (font-size: 0;). What this means is that many browsers handle it unpredictably.

Nihar Sarkar
  • 1,187
  • 1
  • 13
  • 26
0

The answer can be found in this Q & A

By default, an image is rendered inline, like a letter.

It sits on the same line that a, b, c and d sit on.

There is space below that line for the descenders you find on letters like f, j, p and q.

By setting the font-size to 0 all letter heights become 0 so there are no descenders to make space for.

Community
  • 1
  • 1
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • Seems like that method makes [`alt`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-alt) text unreadable, which isn't very accessible. – showdev Aug 12 '16 at 19:03