html - 显示 : inline-flex has greater height than sibling span 的 Span 元素

标签 html css height flexbox

在使用 flex 容器时,我注意到 Chrome 和 Firefox 都以比静态容器高 1px 的高度渲染它。

代码如下:

.container {
  background-color: yellow;
  border: 1px solid red;
}
.main {
  border: 1px solid black;
}
.flex-cont {
  display: inline-flex;
}
<div class="container">
  <span class="main flex-cont">
    		This is the flex container, height is 20px
    	</span>
  <span class="main">
    		This is not the flex container, height is 19px
    	</span>
</div>

在这里 fiddle :http://jsfiddle.net/pzoxfs90/

有人知道这是为什么以及如何避免吗?

最佳答案

默认情况下,您的 span 元素是行内元素。

vertical-align的初始值适用于行内级元素的属性是 baseline。这允许浏览器在元素下方提供一些空间来容纳 descenders .

当您将 display: inline-flex 应用于其中一个跨度时,您会建立一个 flex formatting context .在这种情况下,子元素是 block 化,这意味着行为更像是 block 级元素。

因此,vertical-align 属性不再适用于 span1,但它继续适用于 span2,这就是您仍然看到下行空间的原因。

来自规范(指包装文本的 anonymous box 是 flex 元素):

4. Flex Items

The display value of a flex item is blockified: if the specified display of an in-flow child of an element generating a flex container is an inline-level value, it computes to its block-level equivalent.

最简单的解决方案是让父级成为一个 flex 容器,默认情况下让您的子元素保持内联,并允许您在两者上设置 flex 属性。

.container {
    display: flex;
    background-color: yellow;
    border: 1px solid red;
}

.main {
    border: 1px solid black;
}
<div class="container">
    <span class="main">This is the flex container, height is 20px</span>
    <span class="main">This is not the flex container, height is 19px</span>
</div>

Revised Fiddle

更多详情:

关于html - 显示 : inline-flex has greater height than sibling span 的 Span 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38352014/

相关文章:

javascript - 使用javascript自动检测高度

html - 表格内单个 TD 的 CSS 填充

html - 坚持 HTML block 的响应高度

带有右插入符的 javascript var 会给出奇怪的结果

javascript - HTML - JavaScript - 添加和删除/隐藏元素

html - 我的背景图片在底部被截断

html - 样式定义水平列表,术语在定义之上

jquery - IE 和 FF 中的 $(window).height() 问题

html - Bootstrap form-horizo​​ntal 的垂直间距文本框

javascript - 我想知道为什么2个变量不能进入js