gpt4 book ai didi

html - 为什么需要使用 line-height 属性垂直对齐 2 个以上的元素?

转载 作者:行者123 更新时间:2023-11-28 05:52:09 24 4
gpt4 key购买 nike

我需要垂直对齐一个内联 block 元素,并在 Internet 上看到一个使用 line-height 属性的示例。

代码如下:

HTML

div#line-parent {
display: block;
width: 100%;
height: 100px;
line-height: 100px;
border: 1px dotted #ccc;
background-color: antiquewhite;
text-align: center;
}

div#line-parent:before {
content: "";
display: inline-block;
vertical-align: middle;
}

div.line-child {
display: inline-block;
width: 20%;
line-height: normal;
background-color: brown;
vertical-align: middle;
}
<div id="line-parent">
<div class="line-child">
vertical align using line height
</div>
</div>

但是,如果父级 (#line-parent) 仅包含子级 (.line-child),则子级不会在中间垂直对齐。

为了让子项在父项中垂直对齐,我在父项中添加了 speudo class :before(就像我上面所做的那样),或者在父项中添加了一些文本。

我想知道为什么我们需要添加多个元素才能使这些元素垂直对齐?它是如何工作的?

最佳答案

有一个常见的误解,认为 vertical-align 指的是内联级别元素父元素中的位置。

事实并非如此。

vertical-align 指的是多个内联级别元素在这样的容器内彼此对齐。

来自W3 Spec

The inline-level boxes are aligned vertically according to their 'vertical-align' property. In case they are aligned 'top' or 'bottom', they must be aligned so as to minimize the line box height.

关于html - 为什么需要使用 line-height 属性垂直对齐 2 个以上的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37268829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com