You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Flex元素下未设高度的.box的子元素.item-1百分比高度生效?

问题

.item-1元素的父元素.box并未设置高度,为何.item-1的百分比高度能够生效?

复现代码:

<!DOCTYPE html>
<html lang="zh_CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>高度百分比-工作</title>
  </head>
  <body>
    <style>
      .wrap {
        background-color: #888;
        display: flex;
        align-items: normal;
      }

      .item-1 {
         background-color: pink;
         width: 100px;
         height: 10%;
        /* 生效 高度=400*10% = 40 */
        /* 预期百分比高度不生效,即.item-1最终高度为0 */
      }
      .item-2 {
        height: 400px;
        width: 200px;
        background-color: skyblue;
      }
    </style>
    <div class="wrap">
      <div class="box">
        <div class="item-1"></div>
        <div class="item-2"></div>
      </div>
    </div>
  </body>
</html>
解答

核心原因在于flex布局的特性以及align-items: normal的作用:

  1. flex容器的高度传递:.wrap是flex容器,.box作为它的唯一flex子元素,在align-items: normal的规则下,.box的高度会自动匹配内部内容的最高高度——也就是.item-2设置的400px。虽然.box没有显式写height: 400px,但flex布局已经明确计算出了它的高度值。

  2. 百分比高度的参考规则:CSS中百分比高度生效的前提是父元素存在有效的高度上下文,这个上下文不一定是显式设置的height属性,只要父元素的高度是被明确计算出来的(比如flex布局拉伸、内容撑开的确定高度),就可以作为子元素百分比高度的参考。

所以.item-1的height: 10%会基于.box的计算高度400px来计算,最终得到40px的实际高度,这就是它生效的原因。

内容的提问来源于stack exchange,提问作者FanYa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:17:47