You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tailwind Flex子项宽度适配:内容不足时仍占满父容器区域

解决Flex子项始终占满父容器宽度的问题

要实现无论内部内容长短,左侧子项都填满父容器的剩余宽度(覆盖红框区域),只需调整两处Tailwind类:

  1. 移除父容器的justify-between类:这个属性会让子项两端对齐、中间留白,阻碍左侧子项填充剩余空间。
  2. 将左侧子项的flex-grow替换为flex-1:flex-1等价于flex: 1 1 0%,强制子项从0宽度开始填充所有可用剩余空间,确保无论内容长短都占满对应区域。

修改后的完整代码:

<section class="mx-auto grid max-w-[1200px] grid-cols-1 px-5 pb-10">
    <div class="flex w-full gap-x-6 py-5">
        <div class="flex min-w-0 gap-x-4 flex-1">
            <img class="h-24 w-24 flex-none rounded-md bg-gray-50"
                 src="./assets/images/product-chair.png"
                 alt="">
            <div class="min-w-0 flex-auto">
                <p class="text-sm font-semibold leading-6 text-gray-900">Leslie Alexander</p>
                <p class="mt-1 truncate text-xs leading-5 text-gray-500">leslie.alexander@example.com</p>
            </div>
        </div>
        <div class="hidden shrink-0 sm:flex sm:flex-col sm:items-end">
            <p class="text-sm leading-6 text-gray-900">Co-Founder / CEO</p>
            <p class="mt-1 text-xs leading-5 text-gray-500">Last seen
                <time datetime="2023-01-23T13:23Z">3h ago</time>
            </p>
        </div>
    </div>
</section>

原理说明

  • 移除justify-between后,Flex容器默认采用flex-start布局,子项从左侧开始排列,剩余空间全部留给设置了flex-1的左侧子项。
  • flex-1相比单独的flex-grow,明确设置了flex-basis: 0%,避免子项基于内容宽度计算初始尺寸,确保完全填充剩余空间。

内容的提问来源于stack exchange,提问作者Ricardo Albear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 16:12:44