添加align-items:center后Flex容器内div消失问题求助
问题:添加
align-items: center后Flex子元素消失的解决办法 我想创建一个容器,左右是蓝色div,中间是尺寸更大的紫色div。但添加align-items: center属性后,所有div都消失了,求解决。
我的HTML代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flexbox Playground</title> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap" rel="stylesheet"> <link rel="stylesheet" href="app.css"> </head> <body> <h1>Let's Play With Flexbox</h1> <section id="anotherExample"> <div class="sidebar"></div> <div class="mainContent"></div> <div class="sidebar"></div> </section> </body> </html>
我的CSS代码:
#anotherExample{ width: 90%; height: 500px; margin: 0 auto; border: 5px solid #003049; display: flex; justify-content: center; /*align-items: center;*/ } section .sidebar{ background-color: blue; flex-grow:1 ; flex-basis: 200px; } section .mainContent{ background-color: blueviolet; flex-grow:2 ; flex-basis: 200px; }
原因分析
问题出在flex-basis和align-items: center的组合上:
flex-basis: 200px定义的是子元素在**主轴(水平方向)**的初始尺寸,但你没有给子元素设置垂直方向的高度。- 默认情况下,
align-items的值是stretch,子元素会自动拉伸填满父容器的垂直空间;当你改成align-items: center时,子元素在垂直方向不再拉伸,而它们本身没有高度,所以就会“消失”(实际是高度为0,看不到背景色)。
解决方案
给子元素设置垂直方向的尺寸,让它们在居中时能显示出来,有两种简单方法:
方法1:给子元素添加height: 100%
让子元素占满父容器的垂直高度,同时保持水平居中:
#anotherExample{ width: 90%; height: 500px; margin: 0 auto; border: 5px solid #003049; display: flex; justify-content: center; align-items: center; /* 现在可以启用这行 */ } section .sidebar{ background-color: blue; flex-grow:1 ; flex-basis: 200px; height: 100%; /* 添加高度设置 */ } section .mainContent{ background-color: blueviolet; flex-grow:2 ; flex-basis: 200px; height: 100%; /* 添加高度设置 */ }
方法2:使用align-self: stretch(按需选择)
如果你希望部分子元素居中,部分拉伸,可以给需要保持高度的子元素单独设置:
section .sidebar, section .mainContent { align-self: stretch; }
不过这种方法下,子元素不会垂直居中,而是保持拉伸状态,适合不需要垂直居中但要避免消失的场景。
内容的提问来源于stack exchange,提问作者user19032516
相关产品推荐
相关产品推荐

