【问题标题】:Span element with display: inline-flex has greater height than sibling span带显示的 Span 元素:inline-flex 的高度大于同级 span
【发布时间】:2023-03-02 21:50:01
【问题描述】:

在玩 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>

在这里提琴:http://jsfiddle.net/pzoxfs90/

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

【问题讨论】:

    标签: html css height flexbox


    【解决方案1】:

    似乎是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>

    【讨论】:

      【解决方案2】:

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

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

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

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

      从规范(参考 anonymous box 包装文本并且是弹性项目):

      4. Flex Items

      弹性项目的display 值被阻塞:如果指定 display 一个元素的流入子元素生成一个 flex container 是一个内联级别的值,它计算到它的块级别 等价的。

      最简单的解决方案是让父元素成为一个 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

      更多细节:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-25
        • 2021-12-11
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        • 2020-11-22
        • 2021-03-06
        • 2022-01-17
        相关资源
        最近更新 更多