Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

html - inline-block div with and without text not vertically aligned

I have two divs side by side. Both have the same size and display: inline-block. The only difference between the two is, the first one has some text and the second one is blank.

HTML:

<div>1</div>
<div></div>

CSS:

div {
    display: inline-block;
    border: 1px solid black;
    width: 50px;
    height: 50px;
}

The first div is lower than the second one.

I am aware of all the possible fixes, like adding some text or a &nbsp; to the second div. Adding vertical-align: top fixes this as well, of course.

What I want to know is, can someone explain, why a blank div has a different alignment than a div with some text in it?

JSFiddle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inline-block boxes are,by default vertically aligned such that the baseline of the inline-block box aligns to the baseline of the line box in which it is rendered.

The baseline of an inline-block box with one line of text, is the baseline of that line. More generally, the baseline of an inline-block is the baseline of the last line of text that it contains. But that means that there is no baseline for an inline-block that contains no text.

In such a situation a fall back rule kicks in, and the bottom of the inline-block box is placed on the baseline of its line box.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...