为什么 display: block 和 display: flex 以不同的高度渲染相同的元素? [英] Why do display: block and display: flex render the same element with a different height?
问题描述
所以我有一个里面有一个跨度的 div.我在 div 上设置 display:block 或 display:flex,在 span 上设置小字体.令人惊讶的是,这在 div 上给出了不同的高度.参见示例.
如果我在 body 或 div 上设置较小的字体大小,则两者的高度相等.但是,如果我像示例中那样在跨度上设置较小的字体大小,则 div 会获得不同的高度.怎么来的?我能做些什么吗?
span {字体大小:0.8rem;边框:1px 红色实心;}div {边框:1px 蓝色实心;}
<div style="display:block;"><span>测试文本 1</span>
<div style="display: flex;"><span>测试文本 2</span>
In a 块格式上下文,line-height
属性有所不同.
这是因为 line-height
为块级容器内的行内元素和行框建立了最小高度.
在块格式上下文中,span
是行内级元素,并且 line-height
适用.
在代码示例中,span
上低于 1rem 的任何字体大小都会改变 font-size
,但不会改变 line-height
,保持不变.这就是您在 font-size: .8rem
中看到的.div
的高度不会改变.除非字体大小超过1rem,否则它不会改变.
在 flex 格式上下文,span
是一个弹性项.弹性项目始终是块级元素(无论元素类型如何).根据 flexbox 规范,Flex 项目被屏蔽".因为没有行内元素,line-height
不适用.
此外,弹性容器的初始设置是align-items:stretch
.这意味着 span
设置容器的高度.
总结,通过display:block
,line-height
保持div 高度固定.使用display:flex
,没有line-height
干扰,div自由跟踪span的高度.
一种解决方案:在span
中添加display:block
,消除line-height
问题.
So I have a div with a span inside. And I'm setting display:block or display:flex on the div, and a small font-size on the span. Surprisingly, this is giving different heights on the div. See the example.
If I set the smaller font-size on the body or div then the height of both is equal. But if I set the smaller font-size on the span like in the example, then the divs get different heights. How come? And can I do anything about it?
span {
font-size: 0.8rem;
border: 1px red solid;
}
div {
border: 1px blue solid;
}
<div style="display: block;">
<span>test text 1</span>
</div>
<div style="display: flex;">
<span>test text 2</span>
</div>
In a block formatting context, the line-height
property makes a difference.
This is because line-height
establishes the minimum height for inline-level elements and line boxes inside block-level containers.
In a block formatting context a span
is an inline-level element and line-height
applies.
In the code sample, any font size on the span
below 1rem will change the font-size
, but not the line-height
, which remains fixed. That's what you're seeing with font-size: .8rem
. The height of the div
doesn't change. And it won't change unless the font size exceeds 1rem.
In a flex formatting context, the span
is a flex item. A flex item is always a block-level element (regardless of the element type). Flex items are "blockified", according to the flexbox spec. Because there are no inline-level elements, line-height
doesn't apply.
Also, an initial setting of a flex container is align-items: stretch
. This means that the span
sets the height of the container.
In summary, with display: block
the line-height
keeps the div height fixed. With display: flex
, there is no line-height
interference and the div tracks the height of the span freely.
One solution: Add display: block
to the span
, which eliminates the line-height
issue.
这篇关于为什么 display: block 和 display: flex 以不同的高度渲染相同的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!