0

I am having a hard time understanding how vertical-align:middle works in CSS. All this while I knew it in my head that if there are inline elements (say a span followed by an image and then followed by a span) all sitting side by side:

<span class="align">THIS IS A SPAN </span><img src="https://thinktwisted.com/wp-content/uploads/2020/07/imageResizer.png"><span>THIS IS A SPAN </span>

I would:

 img {
    vertical-align:middle 
} 

and the spans would be vertically align with the image like below:

enter image description here

But what I am failing to understand is how this actually works. Mozilla docs says:

middle: Aligns the middle of the element with the baseline plus half the x-height of the parent

In my case the img tag doesn't have any parent and its parent is the body. In that case where is the baseline to which the middle of the image is aligned? Also, even though I am targetting the img tag the image itself doesn't seem to be affected only the span is moving up to the middle of the image . How is that happening?

Additionally if I target the span itself nothing changes:

span {
            vertical-align: middle;
        }

What is happening when I do that?

How is vertical-align evaluated and which element is actually affected?

halfer
  • 19,824
  • 17
  • 99
  • 186
Knownow
  • 353
  • 1
  • 4
  • 17
  • It probably doesn't help your state of confusion that your image is so massive, that it's dictating the height of the parent container – Caius Jard Dec 21 '20 at 13:09
  • 1
    ps; the MDN article you referenced links to [an article](https://christopheraue.net/design/vertical-align#movement-of-the-line-boxs-baseline) that goes into some depth to explain what you see – Caius Jard Dec 21 '20 at 13:25
  • I'd read the article and understood how the baseline should shift but that doesnt answer my question of why applying vertical - align :middle to the span doesn't shift the baseline and the image isn't moved upwards . I will try anything other than SO to understand this .SO hasn't been very helpful recently . – Knownow Dec 21 '20 at 16:04
  • The span isn't big enough to move the parent item's alignment line. If you have a span that is 10px high align middle and an image 100px high align baseline and a span 10px high align baseline, then you'll find that the left span (and remember that characters hang under a line too, but not in your ALL CAPS trial) is dropped down relative to the base of the image, and the right span's bottom is aligned with the image bottom. The bottoms of the spans will not be aligned, because one is middle and one is baseline (the mid line of the span is higher than its baseline so the span moves down) – Caius Jard Dec 21 '20 at 17:44

0 Answers0