如何用百分比设置HTML表格thead、tbody及tr的高度?
解决表格高度比例分配问题
直接给<thead>加h-[10%]没效果,是因为默认表格布局不会按比例分配高度,得调整布局结构:
修改后的代码
<div class="table-container text-sm w-full h-full overflow-hidden rounded-lg bg-gray-700 select-none text-white"> <table class="w-full h-full flex flex-col"> <thead class="flex-shrink-0 h-[10%]"> <tr class="w-full h-full"> <th class="px-6 py-2 flex items-center">Subreddit</th> <th class="px-6 py-2 flex items-center">New Posts</th> <th class="px-6 py-2 flex items-center">New Comments</th> <th class="px-6 py-2 flex items-center">New Upvotes</th> </tr> </thead> <tbody class="flex-grow h-[90%] overflow-y-auto bg-gray-800 w-full"> <div class="w-full grid grid-rows-[repeat(10,1fr)]"> <tr class="h-[10%] border-b border-gray-700"> <td class="px-6 py-2 flex items-center">funny</td> <td class="px-6 py-2 flex items-center">12312</td> <td class="px-6 py-2 flex items-center">423432</td> <td class="px-6 py-2 flex items-center">23432</td> </tr> <tr class="h-[10%] border-b border-gray-700"> <td class="px-6 py-2 flex items-center">gaming</td> <td class="px-6 py-2 flex items-center">56789</td> <td class="px-6 py-2 flex items-center">98765</td> <td class="px-6 py-2 flex items-center">13579</td> </tr> <!-- 可继续添加至10行,每行都会自动适配10%高度 --> </div> </tbody> </table> </div> <script src="https://cdn.tailwindcss.com"></script>
关键调整说明
- 给
<table>加flex flex-col h-full:将表格改为垂直flex布局,占满容器高度,让<thead>和<tbody>能按比例分配高度。 <thead>加flex-shrink-0 h-[10%]:固定占父容器10%高度,不会被内容挤压;内部<tr>设h-full,<th>加flex items-center实现表头内容垂直居中。<tbody>加flex-grow h-[90%] overflow-y-auto:占剩余90%高度,内容过多时自动滚动;内部嵌套<div>并设置grid-rows-[repeat(10,1fr)],让每个<tr>自动占tbody高度的10%,10行刚好填满区域,不会出现截断。- 每个
<tr>加h-[10%]配合grid布局,<td>加flex items-center保证内容垂直居中。
内容的提问来源于stack exchange,提问作者Michael Xia
相关产品推荐
相关产品推荐

