【问题标题】:Is it possible to have a flex div take the height of its outer container? [duplicate]是否可以让 flex div 获取其外部容器的高度? [复制]
【发布时间】:2022-01-15 09:40:30
【问题描述】:

例如,在下面的小提琴中,我有一个 flex div。

似乎将高度设置为 100% 对 div 没有影响。

默认情况下,div 是显示块,占宽度的 100%。但显然高度的行为不同。

https://jsfiddle.net/02wtuzjp/1/

#expand{
  display: flex;
  height: 100%;
  border: 1px solid red;
}
<div id = 'expand'>
</div>

这似乎是预期行为,因为 div 中没有内容。

https://css-tricks.com/almanac/properties/h/height/

一种解决方案是使用单位vh 或更具体地100vh

但是,我不确定这是正确还是最好的方法。

【问题讨论】:

标签: html css flexbox


【解决方案1】:

具有基于百分比高度的元素需要一个parent reference 来作为其高度的基础。您可以添加:

html, body {
    height: 100%;
}

你的元素将是 100% 的高度:

html,
body {
  height: 100%;
}

#expand {
  display: flex;
  height: 100%;
  border: 1px solid red;
}
<div id="expand">
</div>

根据您的编辑: 您当然可以使用100vh 来设置高度,但是该元素将始终是视口高度的 100%。无论它是否包含元素。

例如:

#random {
  height: 50px;
}

#expand {
  display: flex;
  height: 100vh;
  border: 1px solid red;
}
<div id="random">
</div>
<div id="expand">
</div>

您可以看到expand 元素的高度为 100vh,并创建了一个滚动条,因为高度是视口的高度,而不是剩余空间。

资源: Article on Medium

【讨论】:

  • 这很酷,我通过 css-tricks 发布了一个链接,这让我更加困惑。您能否将您的答案与我在 Q 编辑中发布的链接联系起来。
  • 我在开发时注意到了这种行为,但在任何地方都没有看到它被引用。你能提供一个网络参考 - mdn,堆栈溢出等
  • @user17331023 我的答案中指向parent reference 的链接是MDN。如果您在&lt;percentage&gt; 标题下阅读,您会看到它谈到了containing element。我知道那里有更多信息。我会添加它。
猜你喜欢
  • 1970-01-01
  • 2011-01-02
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多