css制作表
CSS 制作表格的方法
使用 CSS 制作表格可以通过原生 HTML 表格元素结合 CSS 样式,或者通过 display: table 系列属性模拟表格布局。以下是两种常见方法:
使用 HTML 表格元素 + CSS 样式
通过 <table>、<tr>、<td> 等原生标签创建表格,再用 CSS 美化。
<table class="styled-table">
<tr>
<th>标题1</th>
<th>标题2</th>
</tr>
<tr>
<td>内容1</td>
<td>内容2</td>
</tr>
</table>
.styled-table {
width: 100%;
border-collapse: collapse; /* 合并边框 */
}
.styled-table th, .styled-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.styled-table th {
background-color: #f2f2f2;
}
.styled-table tr:nth-child(even) {
background-color: #f9f9f9;
}
使用 display: table 模拟表格
通过 CSS 将非表格元素(如 <div>)模拟为表格结构。
<div class="css-table">
<div class="css-tr">
<div class="css-th">标题1</div>
<div class="css-th">标题2</div>
</div>
<div class="css-tr">
<div class="css-td">内容1</div>
<div class="css-td">内容2</div>
</div>
</div>
.css-table {
display: table;
width: 100%;
}
.css-tr {
display: table-row;
}
.css-th, .css-td {
display: table-cell;
border: 1px solid #ddd;
padding: 8px;
}
.css-th {
font-weight: bold;
background-color: #f2f2f2;
}
响应式表格设计
针对移动端,可通过横向滚动或堆叠布局优化显示。
横向滚动方案
.table-container {
overflow-x: auto;
}
堆叠布局方案
@media (max-width: 600px) {
.css-tr {
display: block;
margin-bottom: 10px;
}
.css-th, .css-td {
display: block;
width: 100%;
}
}
高级样式技巧
- 悬停高亮:
tr:hover { background-color: #eee; } - 斑马纹:
tr:nth-child(odd) { background-color: #f9f9f9; } - 固定表头:通过
position: sticky实现滚动时表头固定。







