css怎样制作表格
CSS 制作表格的方法
使用 CSS 制作表格通常有两种方式:一种是直接使用 HTML 的 <table> 标签结合 CSS 样式,另一种是使用 <div> 或其他元素通过 CSS 的 display: table 系列属性模拟表格布局。
使用 HTML <table> 标签
HTML 原生表格标签结合 CSS 可以快速实现表格布局,适合展示结构化数据。
<table class="custom-table">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>职业</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>25</td>
<td>设计师</td>
</tr>
<tr>
<td>李四</td>
<td>30</td>
<td>工程师</td>
</tr>
</tbody>
</table>
.custom-table {
width: 100%;
border-collapse: collapse; /* 合并边框 */
margin: 20px 0;
font-family: Arial, sans-serif;
}
.custom-table th, .custom-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.custom-table th {
background-color: #f2f2f2;
font-weight: bold;
}
.custom-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.custom-table tr:hover {
background-color: #f1f1f1;
}
使用 CSS display: table 模拟表格
通过 CSS 的表格布局属性,可以用非 <table> 元素实现表格效果,适合需要更灵活的场景。
<div class="css-table">
<div class="css-thead">
<div class="css-tr">
<div class="css-th">姓名</div>
<div class="css-th">年龄</div>
<div class="css-th">职业</div>
</div>
</div>
<div class="css-tbody">
<div class="css-tr">
<div class="css-td">张三</div>
<div class="css-td">25</div>
<div class="css-td">设计师</div>
</div>
<div class="css-tr">
<div class="css-td">李四</div>
<div class="css-td">30</div>
<div class="css-td">工程师</div>
</div>
</div>
</div>
.css-table {
display: table;
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.css-thead {
display: table-header-group;
}
.css-tbody {
display: table-row-group;
}
.css-tr {
display: table-row;
}
.css-th, .css-td {
display: table-cell;
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.css-th {
background-color: #f2f2f2;
font-weight: bold;
}
.css-tr:nth-child(even) {
background-color: #f9f9f9;
}
.css-tr:hover {
background-color: #f1f1f1;
}
响应式表格设计
对于移动端或小屏幕设备,表格可能需要横向滚动或调整布局。

.table-responsive {
overflow-x: auto;
max-width: 100%;
}
@media (max-width: 600px) {
.custom-table, .css-table {
font-size: 14px;
}
}
高级样式技巧
- 斑马纹效果:使用
nth-child(even/odd)为交替行设置不同背景色。 - 悬停效果:通过
:hover伪类增强交互体验。 - 固定表头:结合
position: sticky实现滚动时表头固定。
.custom-table thead th {
position: sticky;
top: 0;
z-index: 10;
}






