React中flex布局justify-content属性不生效问题求助
问题原因与解决方案
你遇到的justify-content不生效的核心原因是容器中的<hr>元素默认样式占据了主轴方向的全部可用宽度,导致两个.card-container被挤压到容器两侧,justify-content无法发挥居中作用。
默认情况下,<hr>是块级元素,宽度为100%,在flex-direction: row的容器中,它会撑满主轴方向的剩余空间,让两个卡片容器失去了被justify-content调整位置的空间。
修复步骤
修改<hr>的CSS样式,将其改为垂直分隔线,避免占用过多主轴空间:
hr { /* 移除默认边框和宽度 */ border: none; width: 2px; /* 设置高度与卡片容器一致 */ height: 300px; /* 添加左右间距,让分隔线和卡片之间有留白 */ margin: 0 20px; background-color: black; }
修改后,你的.container容器中的三个子元素(两个.card-container和<hr>)会在主轴上被justify-content: center均匀居中排列,同时保留分隔线的视觉效果。
验证效果
调整后的完整CSS:
.container{ display: flex; flex-direction: row; align-items: center; justify-content:center; height: 400px; width: 100%; background-color: gray; } .card-container{ width: 200px; height: 300px; background-color: salmon; border: 2px solid black; } .card{ width: 60px; height: 100px; border: 1.5px solid blue; border-radius: 8px; margin: auto; } hr { border: none; width: 2px; height: 300px; margin: 0 20px; background-color: black; }
这样修改后,justify-content: center就能正常生效,两个卡片容器会在灰色容器中水平居中排列,中间有垂直的黑色分隔线。
内容的提问来源于stack exchange,提问作者Eitan Leiberman
相关产品推荐
相关产品推荐

