如何将HTML表格单元格设置为正方形?
实现表格单元格正方形效果的方案
方法1:固定尺寸正方形(适合尺寸固定的场景)
直接给单元格设置相同的宽高即可,修改步骤如下:
- 新增自定义CSS样式
/* 自定义正方形表格样式 */ .table-square { table-layout: fixed; /* 固定表格布局,防止内容撑宽单元格 */ } .table-square th, .table-square td { width: 120px; /* 可根据需求调整尺寸,宽高保持一致即可 */ height: 120px; text-align: center; vertical-align: middle; overflow: hidden; /* 内容超出时隐藏,避免破坏形状 */ }
- 给原有table标签新增自定义类名
把<table class="table table-bordered">修改为<table class="table table-bordered table-square">
方法2:响应式正方形(适配不同屏幕尺寸)
如果需要正方形随页面宽度自适应调整,用百分比padding实现比例固定的正方形:
- 新增自定义CSS样式
.table-square { table-layout: fixed; width: 100%; /* 表格占满父容器宽度 */ } .table-square th, .table-square td { position: relative; width: 33.33%; /* 3列的情况,每列占1/3宽度,列数变化时调整数值 */ height: 0; padding-top: 33.33%; /* padding百分比相对于父元素宽度,和宽度值一致即可形成正方形 */ overflow: hidden; } /* 单元格内容定位 */ .table-square .cell-content { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
- 修改table标签类名,同时把单元格内的内容套入
.cell-content容器,示例:
<td> <div class="cell-content">John</div> </td>
可选:国际象棋棋盘样式
如果要实现你示例图的交替背景效果,可额外添加以下CSS:
.table-square tr:nth-child(odd) td:nth-child(even), .table-square tr:nth-child(even) td:nth-child(odd) { background-color: #ccc; /* 深色格子颜色可自定义 */ }
完整修改后代码示例
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <style> .table-square { table-layout: fixed; } .table-square th, .table-square td { width: 120px; height: 120px; text-align: center; vertical-align: middle; overflow: hidden; } /* 可选棋盘样式 */ .table-square tr:nth-child(odd) td:nth-child(even), .table-square tr:nth-child(even) td:nth-child(odd) { background-color: #ccc; } </style> <table class="table table-bordered table-square"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>Doe</td> <td>john@example.com</td> </tr> <tr> <td>Mary</td> <td>Moe</td> <td>mary@example.com</td> </tr> <tr> <td>July</td> <td>Dooley</td> <td>july@example.com</td> </tr> </tbody> </table>
内容的提问来源于stack exchange,提问作者Kunal Tiwalkar
相关产品推荐
相关产品推荐

