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
相关产品推荐
相关产品推荐

