Cabage Cabage - 3 months ago 9
CSS Question

Why is vertical-align applied to an image also applying to sibling text?

I set the

vertical-align
on the image only.

So the
vertical-align
on the text should be the default
vertical-align: baseline
.

But why is the text moving to top, middle, bottom?



<div style="background-color:#e5edff;">
<img src="http://placehold.it/100x100" style="vertical-align:top;">aaa
</div>
<br>
<div style="background-color:#e5edff;">
<img src="http://placehold.it/100x100" style="vertical-align:middle;">bbb
</div>
<br>
<div style="background-color:#e5edff;">
<img src="http://placehold.it/100x100" style="vertical-align:bottom;">bbb
</div>





The demo on code pen

Answer

Let's break down your code:

<div style="background-color:#e5edff;">
  <img src="http://placehold.it/100x100" style="vertical-align:top;">aaa
</div>

<br>

<div style="background-color:#e5edff;">
   <img src="http://placehold.it/100x100" style="vertical-align:middle;">bbb
</div>

<br>

<div style="background-color:#e5edff;">
   <img src="http://placehold.it/100x100" style="vertical-align:bottom;">bbb
</div>

If you check developer tools, you'll find that the vertical-align property is working as instructed for each img element.

But what's the computed vertical-align value for the anonymous inline box wrapping the text?

It's actually baseline. Anonymous boxes inherit parent properties, and when properties are not inheritable, they use initial values (source). In either case, it's baseline here, and the image's vertical-align is not being applied.

So when you see the text apparently aligned by the image's vertical-align setting (top, middle or bottom), yet the text is actually computing to baseline, it comes off as strange and confusing.

What's actually happening is that the vertical-align setting on the image is moving the baseline of the line box.

Because the image already occupies the full height of the container, vertical-align is having no effect. There's nowhere to move.

In order to complete the task, which is to vertically align the element relative to the line box's baseline, the baseline has to move.

More details: 10.8 Line height calculations: the line-height and vertical-align properties

Comments