为什么带有内容的 div 在 inline-block 中向下移动? [英] Why does div with content move down in inline-block?

查看:35
本文介绍了为什么带有内容的 div 在 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-alignbaseline*.

这张来自
如您所见,基线不是文本向下走多远,而是文本对齐的行.使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆