为什么display:block和display:flex渲染具有不同高度的相同元素? [英] Why do display: block and display: flex render the same element with a different height?

查看:987
本文介绍了为什么display:block和display:flex渲染具有不同高度的相同元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个div,里面有一个span.我在div上设置display:block或display:flex,在span上设置小字体.令人惊讶的是,这在div上给出了不同的高度.参见示例.

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.

如果在body或div上设置较小的字体大小,则两者的高度相等.但是,如果像示例中那样在跨度上设置较小的字体大小,则div会具有不同的高度.怎么会?而且我能做些什么吗?

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.

这是因为line-height为块级容器内的行内元素和行框确定了最小高度.

This is because line-height establishes the minimum height for inline-level elements and line boxes inside block-level containers.

在块格式化上下文中,span是内联级别的元素,并且line-height适用.

In a block formatting context a span is an inline-level element and line-height applies.

在代码示例中,1rem以下的span上的任何字体大小都会更改font-size,但不会更改line-height,该字体保持不变.这就是您在font-size: .8rem中看到的内容. div的高度不变.除非字体大小超过1rem,否则它不会改变.

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.

flex格式设置上下文中 span是弹性项目.弹性项目始终是块级元素(无论元素类型如何).根据 flexbox规范,Flex项被阻止". .因为没有内联级元素,所以line-height不适用.

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.

此外,flex容器的初始设置为align-items: stretch.这意味着span设置容器的高度.

Also, an initial setting of a flex container is align-items: stretch. This means that the span sets the height of the container.

总结,使用display: blockline-height可使div高度保持固定.使用display: flex时,不会出现line-height干扰,并且div可自由跟踪跨度的高度.

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.

一种解决方案:将display: block添加到span中,这消除了line-height问题.

One solution: Add display: block to the span, which eliminates the line-height issue.

这篇关于为什么display:block和display:flex渲染具有不同高度的相同元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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