为什么带有内容的 div 在 inline-block 中向下移动? [英] Why does div with content move down in inline-block?
问题描述
我有 3 个像这样的 div:
<div class="div2"></div><div class="div3"></div>
具有以下 CSS:
div {边框:1px纯黑色;显示:内联块;高度:100px;宽度:100px;}
当 div 为空时,此代码工作正常.所有 div 都沿同一水平面对齐.但!当我将任何内容放在 1 或 2 个 div 中时,带有内容的 div 会向下移动大约 90% 的高度:
X<div class="div2">Y</div><div class="div3"></div>
与通常对齐的 div 3 相比,Divs 1 和 2 现在被隔开.当我向最终 div 添加内容时,情节真的变厚了:
X<div class="div2">Y</div><div class="div3">Z</div>
现在所有三个 div 都再次在页面顶部正确对齐.不确定这里发生了什么或正确的解决方法?
发生这种情况是因为内联块元素的默认 vertical-align
是 baseline
*.
这张来自
如您所见,基线不是文本向下走多远,而是文本对齐的行.使用 vertical-align:baseline
,没有内容的 div 与由
这张图片可以帮助你想象发生了什么(
为了让你所有的
vertical-align:top;
:div {边框:1px纯黑色;显示:内联块;高度:100px;宽度:100px;垂直对齐:顶部;}
<小时>*
W3 规范一个>
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?
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:
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):
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
这篇关于为什么带有内容的 div 在 inline-block 中向下移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!