CSS 踩坑(1)—— flex-direction: column 与 height
date
Sep 16, 2022
slug
height-not-work-when-parent-is-flex-column
status
Published
tags
Frontend
CSS
summary
同时为 flex-direction: column 容器和其子元素设置高度时子元素的高度设置失效。
type
Post
问题介绍
现在有下面的 HTML 和 CSS:
<div class="flex-container">
<div class="super-height">
I'm a super height element.
</div>
</div>
.flex-container {
display: flex;
height: 100px;
justify-content: center;
flex-direction: column;
}
.super-height {
height: 8888px;
background: whitesmoke;
width: 100%;
}
CSS 中为
.flex-container
和 .super-height
都设置了 height
属性,所以预期的话 .super-height
应该是 8888px。而实际表现见下图:

这是由于
.super-height
元素的父元素设置了 flex-direction: column
导致 .super-height
的高度设置失效了而跟随了父元素的高度设置。具体可见 DEMO:

解决方案
如果遇到类似的场景,可以将 flex 容器的
flex-wrap
设置为 wrap
,同时配合子元素的宽度设置以达到相同的目的。