Tailwind CSS 表格
虽然现代 Web 设计中,复杂的数据展示有时会用卡片式布局代替,但传统表格在显示结构化数据时仍然是不可或缺的。Tailwind 提供了一些工具类来帮助你快速构建美观、响应式的表格。
基本表格样式
一个基础的、带有边框的表格可以通过组合使用边框、内边距和文本对齐工具类来创建。
html
<div class="overflow-x-auto">
<table class="min-w-full text-sm divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Title</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Role</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr>
<td class="px-6 py-4 whitespace-nowrap">Jane Cooper</td>
<td class="px-6 py-4 whitespace-nowrap">Regional Paradigm Technician</td>
<td class="px-6 py-4 whitespace-nowrap">jane.cooper@example.com</td>
<td class="px-6 py-4 whitespace-nowrap">Admin</td>
</tr>
<!-- More people... -->
</tbody>
</table>
</div>关键工具类解析:
min-w-full: 确保表格在小屏幕上至少和容器一样宽,可以与overflow-x-auto结合实现水平滚动。divide-y divide-gray-200: 在tbody和thead中,为行与行之间添加灰色的上边框,形成分割线。px-6 py-4: 为单元格(th和td)提供舒适的内边距。text-left: 默认情况下th是居中的,这里统一设为左对齐。whitespace-nowrap: 防止单元格内容换行,保持表格整洁。
表格布局
使用 table-auto 和 table-fixed 来控制表格的布局算法。
table-auto(默认): 浏览器会根据单元格的内容来计算列宽。内容多的列会更宽。这通常能得到不错的结果,但如果内容长度变化很大,可能会导致布局跳动。table-fixed: 表格和列的宽度由其自身的宽度或第一行单元格的宽度决定。它会忽略内容的大小。这通常更快,并且能提供更可预测的布局。
html
<table class="table-fixed w-full">
<colgroup>
<col class="w-1/2">
<col class="w-1/4">
<col class="w-1/4">
</colgroup>
<thead>
<!-- ... -->
</thead>
<tbody>
<!-- ... -->
</tbody>
</table>在 table-fixed 模式下,你可以精确地为每一列设置宽度。
边框折叠
使用 border-collapse 和 border-separate 来控制表格边框是合并还是分离。
border-collapse: (默认) 相邻单元格的边框会合并成一个单一的边框。这是最常见的样式。border-separate: 边框是分离的。你可以使用border-spacing-x-{size}和border-spacing-y-{size}来控制边框之间的距离。
html
<table class="border-separate border-spacing-2 border border-slate-500 ...">
<!-- ... -->
</table>斑马条纹
使用 odd 和 even 变体可以轻松创建斑马条纹(隔行变色)的表格,提高可读性。
html
<tbody class="bg-white divide-y divide-gray-200">
<!-- ... -->
<tr class="odd:bg-white even:bg-slate-50">
<!-- ... -->
</tr>
<!-- ... -->
</tbody>通过组合这些核心的表格、边框和颜色工具类,你可以构建出满足各种需求的、清晰易读的数据表格。