如何让垂直排列的Flex元素宽度一致且保持items-end对齐?
问题:让垂直排列的窄元素与宽元素同宽(保留
items-end) 我有两个垂直排列的元素,希望较窄的元素与较宽的元素宽度相同。当前代码如下:
<div class="flex flex-col items-end"> <div>This should take all the space</div> <div class="flex flex-row gap-x-4"> <div> this is the first element</div> <div> this is the second element</div> </div> </div>
我需要第一个元素和第二个元素宽度一致,同时必须保留items-end类让元素靠页面右侧显示,尝试调整定位后未达到预期效果,求解决办法。
解决方案
给父容器添加w-fit属性,让其宽度由内部最宽的子元素决定,再给需要拉伸的第一个子元素加上w-full,使其撑满父容器宽度,从而和第二个元素保持一致:
修改后的代码:
<div class="flex flex-col items-end w-fit"> <div class="w-full">This should take all the space</div> <div class="flex flex-row gap-x-4"> <div> this is the first element</div> <div> this is the second element</div> </div> </div>
原理说明:
w-fit:让父容器的宽度自动适配内部最宽的子元素(这里就是第二个横向排列的div)w-full:让第一个子元素的宽度铺满父容器,从而和第二个元素宽度对齐- 原有的
items-end类被保留,确保整个容器依然靠右对齐
内容的提问来源于stack exchange,提问作者Sig
相关产品推荐
相关产品推荐

