如何实现HTML表格不与上下边框相连的侧边非闭合边框?
实现效果说明
完全可以实现你需要的侧边纵向边框不与表格顶底边框连接的效果,以下是两种常见实现方案:
方案1:基于表格自带边框属性调整
实现逻辑:关闭表格默认的边框合并规则,仅对单元格设置左右边框,配合上下内边距实现断开效果,适合简单场景使用。
.custom-table { border-collapse: separate; border-spacing: 0; border-top: 1px solid #333; border-bottom: 1px solid #333; width: 100%; } .custom-table td, .custom-table th { padding: 10px 15px; } /* 给每行首尾单元格加左右边框 */ .custom-table tr td:first-child, .custom-table tr th:first-child { border-left: 1px solid #333; } .custom-table tr td:last-child, .custom-table tr th:last-child { border-right: 1px solid #333; } /* 首行上侧、末行下侧留空实现断开效果 */ .custom-table tr:first-child td, .custom-table tr:first-child th { padding-top: 12px; } .custom-table tr:last-child td, .custom-table tr:last-child th { padding-bottom: 12px; }
方案2:伪元素实现(更灵活,推荐)
实现逻辑:给表格套一层外层容器,用容器的伪元素单独绘制左右侧边边框,直接调整伪元素的上下偏移量即可精准控制断开距离,不会影响表格本身的样式逻辑,兼容大部分业务场景。
<style> .table-wrap { position: relative; display: inline-block; } .custom-table { border-collapse: collapse; border-top: 1px solid #333; border-bottom: 1px solid #333; width: 400px; } .custom-table td, .custom-table th { padding: 10px 15px; text-align: left; } /* 绘制左右侧边边框 */ .table-wrap::before, .table-wrap::after { content: ""; position: absolute; /* 上下各偏移6px,实现和顶底边框断开 */ top: 6px; bottom: 6px; width: 1px; background-color: #333; } .table-wrap::before { left: 0; } .table-wrap::after { right: 0; } </style> <div class="table-wrap"> <table class="custom-table"> <tr> <th>列1</th> <th>列2</th> <th>列3</th> </tr> <tr> <td>测试内容1</td> <td>测试内容2</td> <td>测试内容3</td> </tr> <tr> <td>测试内容4</td> <td>测试内容5</td> <td>测试内容6</td> </tr> </table> </div>
内容的提问来源于stack exchange,提问作者user5507535
相关产品推荐
相关产品推荐

