Flexbox子元素未等高咨询:为何默认align-stretch行为未生效?
为什么我的Flexbox子元素没有等高?
嘿,我一眼就瞅出问题在哪了!你说的没错,flex容器在flex-row布局下,交叉轴的默认对齐方式确实是align-stretch——也就是子元素会自动拉伸到和最高的那个一样高,但你给父容器加了items-center这个Tailwind类,这直接把交叉轴对齐方式改成了垂直居中,完全覆盖了默认的拉伸行为,这就是红色元素没和蓝色元素等高的原因!
先看你贴的代码:
<div class="flex w-full items-center flex-wrap"> <div class="flex flex-col md:w-1/2 items-center px-16 py-20 bg-red"> <h2 class="marjan-col">Smaller text</h2> <p>This one has smaller text</p> </div> <div class="flex flex-col md:w-1/2 items-center px-16 py-20 bg-blue"> <h2 class="text-white">Bigger text that controls element height</h2> <p class="text-white"> Blue element has more text thus making red element smaller and unable to fit entire height </p> </div> </div>
父容器的items-center会让所有子元素在垂直方向上居中对齐,父容器的高度虽然由蓝色元素撑起来了,但红色元素只会保持自身内容的高度,不会主动拉伸填满父容器的高度。
给你两个解决办法,选哪个看你的需求:
方案一:移除父容器的items-center,让子元素内容内部居中
把父容器的items-center删掉,恢复默认的align-stretch,这样两个子元素会自动等高。如果想让子元素内部的文字垂直居中,给每个子元素加上justify-center就行:
<div class="flex w-full flex-wrap"> <div class="flex flex-col md:w-1/2 items-center justify-center px-16 py-20 bg-red"> <h2 class="marjan-col">Smaller text</h2> <p>This one has smaller text</p> </div> <div class="flex flex-col md:w-1/2 items-center justify-center px-16 py-20 bg-blue"> <h2 class="text-white">Bigger text that controls element height</h2> <p class="text-white"> Blue element has more text thus making red element smaller and unable to fit entire height </p> </div> </div>
方案二:保留父容器的items-center,强制子元素占满高度
如果一定要保留父容器的垂直居中对齐,那给两个子元素都加上h-full类,让它们强制继承父容器的高度,这样也能实现等高:
<div class="flex w-full items-center flex-wrap"> <div class="flex flex-col md:w-1/2 items-center h-full px-16 py-20 bg-red"> <h2 class="marjan-col">Smaller text</h2> <p>This one has smaller text</p> </div> <div class="flex flex-col md:w-1/2 items-center h-full px-16 py-20 bg-blue"> <h2 class="text-white">Bigger text that controls element height</h2> <p class="text-white"> Blue element has more text thus making red element smaller and unable to fit entire height </p> </div> </div>
核心就是搞清楚:items-center会覆盖默认的拉伸行为,要么去掉它换子元素内部的居中,要么强制子元素占满高度就行~
内容的提问来源于stack exchange,提问作者Idiot
相关产品推荐
相关产品推荐

