嵌套Flexbox布局问题求助:内层元素未按预期排列
嵌套Flexbox布局问题解决
问题说明
需要实现三个div(Div 1、Div 2、Div 3)水平均匀分布,同时中间div内的两段文本垂直均匀分布,但当前中间容器内的段落未按预期排列。
原代码问题分析
.text类存在拼写错误:weight应为width- 嵌套Flex容器(
.text)无明确高度,justify-content: space-between需要容器有高度才能生效 - 父容器
.container的align-items: flex-start会让子元素高度自适应内容,导致中间容器无法和另外两个div等高,垂直分布效果无法体现
修正后的代码
HTML代码
<!DOCTYPE html> <html lang="en"> <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>Document</title> <link rel="stylesheet" href="test.css"> </head> <body> <div class="container"> <div>Div 1</div> <div class="text"> <p>abc</p> <p>def</p> </div> <div>Div 3</div> </div> </body> </html>
CSS代码
.container { display: flex; flex-direction: row; justify-content: space-evenly; align-items: stretch; /* 修改为stretch,让子元素高度一致 */ min-height: 100vh; /* 让容器占满视口高度,确保垂直分布效果明显 */ } .text { flex: 1; display: flex; flex-direction: column; justify-content: space-between; width: 100%; /* 修正拼写错误 */ padding: 0 1rem; /* 可选:添加内边距优化文本显示 */ }
关键修改点
- 将
.container的align-items改为stretch,使三个子div高度一致 - 修正
.text中的拼写错误,把weight改为width - 给
.container设置min-height: 100vh,让嵌套Flex容器有足够高度实现垂直方向的space-between分布
内容的提问来源于stack exchange,提问作者mkmkmkmk
相关产品推荐
相关产品推荐

