为何align-items属性不生效?元素始终处于页面顶部
Flexbox对齐问题解决办法
问题根源
你的代码里有两个关键问题导致align-items无法生效:
- flex容器默认高度仅包裹内部内容,没有多余垂直空间让项目实现对齐效果
- 混淆了
align-content和align-items的用法,当前单行布局场景下不该使用align-content
具体修正步骤
- 给flex容器设置垂直高度
默认情况下.container的高度和内部元素高度一致,就算设置垂直对齐也看不到变化。你可以给容器设置占满整个视口的高度:
.container { display: flex; flex-direction: row; align-items: center; /* 替换原来的align-content */ justify-content: space-evenly; height: 100vh; /* 让容器高度等于视口高度 */ }
修正对齐属性
align-content是用来控制多行flex项目之间的垂直间距的,必须配合flex-wrap: wrap才会生效。你的布局是单行结构,应该用align-items: center来控制项目在垂直方向的对齐。额外优化:清除默认边距
浏览器默认给body设置了margin,会导致100vh高度的容器出现滚动条,建议补充:
body { margin: 0; }
修正后的完整代码
CSS
body { margin: 0; } .box-1 { background-color: green; border-radius: 1rem; padding-left: 25px; padding-right: 25px; width: 50px; height: 100px; } .box-2 { background-color: green; padding-left: 25px; border-radius: 1rem; padding-right: 25px; width: 50px; height: 100px; } .box-3 { background-color: green; border-radius: 1rem; padding-left: 25px; padding-right: 25px; width: 50px; height: 100px; } .container { display: flex; flex-direction: row; align-items: center; justify-content: space-evenly; height: 100vh; }
HTML
<div class="container"> <div class="box-1">Item 1</div> <div class="box-2">Item 2</div> <div class="box-3">Item 3</div> </div>
内容的提问来源于stack exchange,提问作者ModernPrograms
相关产品推荐
相关产品推荐

