What's the deal with vertical-align: baseline?

后端 未结 3 915
野的像风
野的像风 2020-12-07 20:48

I thought I knew my way around CSS, but I needed to explain something to someone just now and I found I couldn\'t.

My question basically boils down to: why is

3条回答
  •  旧时难觅i
    2020-12-07 21:39

    The question is why are vertical-align: baseline; ignored. Well I don't think it is. In your first snippet you're using baseline and bottom what clearly gives a difference between the two elements. So what does baseline do? Well baseline Aligns the baseline of the element with the baseline of the parent element. In the example below I've copied and adjusted some parts to give the difference.

    span.one {vertical-align:baseline}
    span.two {vertical-align:middle;}

    one two

    As you can see the baseline alignment acts normal just as the middle alignment.

    Now lets test something else. lets swap the alignment of baseline and middle and edit middle and add a third

    span.one { vertical-align: top;}
    span.two { vertical-align: baseline;}
    
    span.three {vertical-align: middle; height: 20px; }
    p {
    height: 50px;
    background-color: grey;
    }

    one two two

    three

    Now if you'll edit the second snippet and take a look at the vertical-align of you can clearly see that when changing the alignment the text does change it's position.

    But you're question relates on text on the same line so lets take a look at the snippet down below.

    span.one { vertical-align: middle;}
    span.two { vertical-align: baseline;}
    
    span.three {vertical-align: middle; height: 20px; }
    p {
    height: 50px;
    background-color: grey;
    }

    one two twothree

    As you can see in this third snippet I've placed the third next to one and two. And it does make a difference. The baseline in this case is different from the middle alignment. This is because the baseline grabs the baseline of the parent. since the parent's height is normal it doesn't affect baseline and top alignment. but when you'll use middle or sub it is clearly a difference.

    For information about each alignment, check out this link.

提交回复
热议问题