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

TailwindCSS如何设置flex子项自动均等填充整个父容器宽度

解决方法

可以通过Tailwind原生的Flex伸缩属性实现子项宽度自动适配,无需手动计算:

方案1:最简适配(推荐)

保留现有父容器的间距配置,仅需将子项的硬编码宽度类w-1替换为flex-1即可。
flex-1对应的CSS规则为flex: 1 1 0%,会自动将父容器扣除所有间距后的剩余空间均等分配给每个子项,子项数量变化时也会自动调整宽度,完全符合需求。
修改后的核心代码如下:

const Status = () => {
  // 可自行修改子项数量测试适配效果
  const barCount = 30;
  return (
    <div className='h-screen bg-gray-800 flex justify-center items-center p-16'>
      <div className='bg-gray-700 px-8 py-4 rounded w-full'>
        <h2 className='text-2xl text-gray-100 font-medium'>Plex Server</h2>
        <h3 className='text-base text-gray-400'>Added 22/10/2021</h3>
        <div className='flex flex-row w-full space-x-1 my-4'>
          {[...Array(barCount)].map((i, idx) => (
            <div key={idx} className='h-8 flex-1 bg-green-400 rounded'></div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Status;

方案2:固定宽度计算

如果你需要严格控制子项不可伸缩,也可以通过动态计算宽度实现,配合Tailwind的自定义类语法使用:

const Status = () => {
  const barCount = 10;
  // 每个子项宽度 = (父容器总宽度 - 所有间距总宽度) / 子项数量
  const barWidth = `calc((100% - ${(barCount - 1) * 4}px) / ${barCount})`;
  return (
    <div className='h-screen bg-gray-800 flex justify-center items-center p-16'>
      <div className='bg-gray-700 px-8 py-4 rounded w-full'>
        <h2 className='text-2xl text-gray-100 font-medium'>Plex Server</h2>
        <h3 className='text-base text-gray-400'>Added 22/10/2021</h3>
        <div className='flex flex-row w-full space-x-1 my-4'>
          {[...Array(barCount)].map((i, idx) => (
            <div key={idx} className={`h-8 w-[${barWidth}] bg-green-400 rounded`}></div>
          ))}
        </div>
      </div>
    </div>
  );
};

内容的提问来源于stack exchange,提问作者Paul Ulibro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:15:06