为何flex布局下.box类的height属性不生效?如何设置高度?
问题分析
高度不生效的原因:
你给body设置了display: flex+flex-direction: column,还固定了height: 100vh。在垂直方向的Flex布局里,子元素(也就是你的.box)默认会被容器的高度限制,再加上默认的flex-shrink: 1,当容器空间不够时,元素会被自动压缩,导致你设置的height: 2000px完全失效。无法并排的原因:
当前body的flex-direction: column是垂直排列子元素,自然没法让.box横向并排。
解决方案
方案一:直接调整body的Flex配置
如果想让body直接作为并排容器,改一下这些属性就行:
body { margin: 0; padding: 0; font-family: "Roboto", sans-serif; min-height: 100vh; /* 把固定height改成min-height,允许容器随内容撑开 */ display: flex; flex-direction: row; /* 改成水平排列 */ align-items: flex-start; /* 不让.box被强制拉伸到容器高度 */ justify-content: center; /* 水平居中排列 */ background-color: #f6f6f6; flex-wrap: wrap; /* 可选:屏幕窄时自动换行 */ } h1 { margin: 10px; width: 100%; /* 让标题独占一行 */ text-align: center; } .box { color: #fff; background-color: steelblue; height: 2000px; width: 300px; padding: 20px; display: flex; align-items: center; justify-content: center; margin: 20px; border-radius: 10px; font-size: 20px; box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.3); flex-shrink: 0; /* 禁止.box被压缩,保证高度生效 */ }
方案二:嵌套Flex容器(更推荐,布局更清晰)
保留body的原有垂直布局,新增一个容器专门负责.box的水平排列,结构更规整:
body { margin: 0; padding: 0; font-family: "Roboto", sans-serif; min-height: 100vh; display: flex; flex-direction: column; align-items: center; background-color: #f6f6f6; } h1 { margin: 10px; } /* 新增的并排容器 */ .box-wrap { display: flex; justify-content: center; flex-wrap: wrap; /* 可选:窄屏自动换行 */ } .box { color: #fff; background-color: steelblue; height: 2000px; width: 300px; padding: 20px; display: flex; align-items: center; justify-content: center; margin: 20px; border-radius: 10px; font-size: 20px; box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.3); flex-shrink: 0; /* 确保高度不被压缩 */ }
对应的HTML要改成这样:
<body> <h1>Scroll Animation</h1> <div class="box-wrap"> <div class="box"> <h2>content</h2> </div> <div class="box"> <h2>content</h2> </div> <div class="box"> <h2>content</h2> </div> </div> </body>
核心注意点
- 不要给
body设置固定height: 100vh,改用min-height: 100vh,这样容器既能占满视口,又能随内容高度撑开。 - 必须给
.box加flex-shrink: 0,否则Flex布局会自动压缩它的高度来适应容器。 - 实现并排的核心是让父容器的
flex-direction为row,要么改body的,要么新增一个专门的容器,后者更利于后续扩展布局。
内容的提问来源于stack exchange,提问作者Smile
相关产品推荐
相关产品推荐

