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

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...