Flex布局无法同时实现垂直与水平居中问题排查
问题:Flex布局设置
flex-direction: column时垂直居中失效 已将html、body、#root及section的高度均设置为100%,section使用flex布局并设置flex-direction: column,同时配置justify-items: center与align-items: center,但内部的h1和form无法实现垂直居中;移除flex-direction: column后,垂直居中生效但水平居中失效。
代码示例:
* { margin: 0; padding: 0; box-sizing: border-box; } html { font-size: 62.5%; height: 100%; } body { font: 1.6rem arial, sans-serif; height: 100%; } #root { height: 100%; } h1, form { width: 50px; height: 50px; } section{ max-width: 50%; height: 100%; display: flex; flex-direction: column; background-color: grey; justify-items: center; align-items: center; }
<div id=root> <section> <h1>Lista Tarefas</h1> <form> <input type="text" /> <button type=" submit ">Enviar</button> </form> </section> </div>
问题原因
justify-items是Grid布局的属性,对Flex容器完全无效。Flex布局中,控制主轴对齐的是justify-content,且主轴方向会随flex-direction改变:
- 默认
flex-direction: row时,主轴为水平方向,justify-content管水平对齐,align-items管垂直对齐 - 设置
flex-direction: column时,主轴变为垂直方向,justify-content管垂直对齐,align-items管水平对齐
修复方案
把section中的justify-items: center替换为justify-content: center即可,修改后的section样式:
section{ max-width: 50%; height: 100%; display: flex; flex-direction: column; background-color: grey; justify-content: center; align-items: center; }
修改后,元素会在垂直方向(主轴)通过justify-content: center居中,水平方向通过align-items: center居中,完全满足需求。
内容的提问来源于stack exchange,提问作者Gabriel Santos
相关产品推荐
相关产品推荐

