带有"display: inline-flex"属性的span元素比同级别的span元素高。

5

在使用flex容器时,我发现Chrome和Firefox渲染的高度比静态兄弟元素多1像素。

以下是代码:

.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>

这里有个示例链接:http://jsfiddle.net/pzoxfs90/

有人知道这是为什么吗?如何避免这种情况?

2个回答

5

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

vertical-align属性的初始值适用于内联级元素,为baseline。这允许浏览器在元素下方提供一些空间以容纳下降字母

当您将display: inline-flex应用于其中一个元素时,您建立了一个flex格式上下文。在这种情况下,子元素会被块化,这意味着行为更像块级元素。

因此,vertical-align属性不再适用于span1,但它仍然适用于span2,这就是为什么您仍然看到下降字母空间的原因。

从规范中(指用于包装文本并作为 flex 项的 匿名框):

4. Flex 项

flex 项的 display 值被块化:如果生成 flex 容器的元素的内部流子级的指定 display 是行级值,则计算为其块级等效项。

最简单的解决方案是将父元素设置为 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>

修订版 Fiddle

更多细节:


0

似乎是一个display:inline;问题,将其更改为display:inline-block;可以解决高度差异。不确定这有多有用...

body {
  margin: 30px;
} 

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

.main {
  border: 1px solid black;
  display:inline-block;    
}

.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 20px
 </span>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接