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

如何在HTML中用Tailwind CSS设置表格行高度为总高度的10%?

问题分析与解决方案

问题根源

你给<tr>设置h-[10%]无效的原因有两个:

  1. 百分比高度依赖父级明确高度:你的表格未设置h-full,导致<tr>的父级(<thead>/<tbody>)没有明确高度基准,百分比值无法计算生效。
  2. 原生表格布局限制:默认的table-auto布局会根据内容自动调整行高,强制忽略百分比高度设置。

解决代码

要实现每行占容器10%高度、最多容纳10行的效果,需要用Flex布局重构表格结构,强制均分高度:

export const Table = () => {
  const employees: Employee[] = [
    { name: "John Doe", position: "Manager", employed: "23/04/18" },
    { name: "Alex Nar", position: "Software Engineer", employed: "23/04/18" }
    // 可添加更多数据测试10行效果
  ]

  return (
    <div className="w-1/2 h-1/2 overflow-scroll text-gray-700 bg-white shadow-md rounded-xl">
      <table className="w-full text-left min-w-max h-full flex flex-col">
        <thead className="flex-shrink-0">
          <tr className="h-[10%] w-full">
            <Cell section="head" content="Name" />
            <Cell section="head" content="Position" />
            <Cell section="head" content="Employed" />
            <Cell section="head" content="" />
          </tr>
        </thead>
        <tbody className="flex-grow flex flex-col">
          {employees.map((employee, index) => (
            <tr key={index} className="h-[10%] w-full">
              <Cell section="body" content={employee.name} />
              <Cell section="body" content={employee.position} />
              <Cell section="body" content={employee.employed} />
              <Cell section="body" content="Edit" />
            </tr>
          ))}
          {/* 数据不足时补全空行,确保总高度占满容器 */}
          {Array.from({ length: Math.max(0, 10 - employees.length) }).map((_, idx) => (
            <tr key={`empty-${idx}`} className="h-[10%] w-full">
              <Cell section="body" content="" />
              <Cell section="body" content="" />
              <Cell section="body" content="" />
              <Cell section="body" content="" />
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

关键修改说明

  • 给<table>添加h-full flex flex-col:让表格占满容器高度,同时启用Flex布局来精准控制行高
  • <thead>加flex-shrink-0:避免表头被内容压缩变形
  • <tbody>加flex-grow flex flex-col:让tbody填充容器剩余高度,内部行自动均分高度
  • 每个<tr>加w-full:保证行宽占满表格,避免Flex布局下的宽度塌陷问题
  • 空行补全逻辑:即使数据不足10行,也能填满容器,保持每行10%高度的视觉一致性

额外注意事项

  • 确保外层容器的父元素(如html/body)设置了h-full,否则h-1/2无法正确计算高度
  • 如果<Cell>组件有默认内边距或固定高度,需要调整其样式(比如加h-full),避免超出<tr>的高度

内容的提问来源于stack exchange,提问作者Michael Xia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:34:58