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。而实际表现见下图:
![notion image](https://www.notion.so/image/https%3A%2F%2Ffile.notion.so%2Ff%2Ff%2Ff384860f-3f6e-4fd5-b42f-c54d32d8bf48%2F4a3f472b-0b7c-420a-b205-75663fd43e65%2F1280X1280.png%3Fid%3D86a2067f-ed54-43db-92af-029bc7335c28%26table%3Dblock%26spaceId%3Df384860f-3f6e-4fd5-b42f-c54d32d8bf48%26expirationTimestamp%3D1722146400000%26signature%3DMhTGd1n8j31XI9EMeWbmA9zNmpTY-2sVM1gnp56qd8A?table=block&id=86a2067f-ed54-43db-92af-029bc7335c28&cache=v2)
这是由于
.super-height
元素的父元素设置了 flex-direction: column
导致 .super-height
的高度设置失效了而跟随了父元素的高度设置。具体可见 DEMO:
![notion image](https://www.notion.so/image/https%3A%2F%2Ffile.notion.so%2Ff%2Ff%2Ff384860f-3f6e-4fd5-b42f-c54d32d8bf48%2F1c0c6c6c-ed2b-46dc-aacf-b4623ed03e8a%2FUnknown-2.gif%3Fid%3D2df5cfcb-f07d-41cb-bfb4-2540fce5a8d4%26table%3Dblock%26spaceId%3Df384860f-3f6e-4fd5-b42f-c54d32d8bf48%26expirationTimestamp%3D1722146400000%26signature%3DN7KMrnguYOa5iGOuzjG-7Z0PEKRYYYcZVTq3YFp0j4M?table=block&id=2df5cfcb-f07d-41cb-bfb4-2540fce5a8d4&cache=v2)
解决方案
如果遇到类似的场景,可以将 flex 容器的
flex-wrap
设置为 wrap
,同时配合子元素的宽度设置以达到相同的目的。