Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - Why does div with content move down in inline-block?

I have 3 divs like so:

<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>

with the following CSS:

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

When the divs are empty, this code works fine. All divs align along the same horizontal plane. But! When I put any content in 1 or 2 divs, the divs with the content move down about 90% of the height:

<div class="div1">X</div>
<div class="div2">Y</div>
<div class="div3"></div>

Divs 1 and 2 are now spaced down in comparison to the normally aligned div 3. The plot really thickens when I add content to the final div:

<div class="div1">X</div>
<div class="div2">Y</div>
<div class="div3">Z</div>

Now all three divs are properly aligned at page top again. Not sure what's happening here or the proper work around?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is happening because the default vertical-align for a inline block element is baseline*.

This image from CSS Tricks helps to demonstrate the baseline of text: baseline demo
As you can see, the baseline isn't how far down the text goes, it is the line that the text is aligned on. With vertical-align:baseline, the div with no content aligns with the baseline created by the <div>'s with content.

This image may help you visualize what's happening(or, you can play with the jsfiddle):

baseline demo2

To make all your <div>'s align, no matter the content, set vertical-align:top;:

div {
  border: 1px solid black;
  display: inline-block;
  height: 100px;
  width: 100px;
  vertical-align:top;
}

This article also helps explain vertical-align some more


* W3 Specs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...