css表格制作
CSS表格制作方法
使用CSS创建表格可以通过多种方式实现,以下是常见的几种方法:
使用HTML原生表格标签结合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 tr:nth-child(even) {
background-color: #f2f2f2;
}
.styled-table th {
background-color: #4CAF50;
color: white;
}
使用div模拟表格布局
<div class="table">
<div class="row header">
<div class="cell">标题1</div>
<div class="cell">标题2</div>
</div>
<div class="row">
<div class="cell">内容1</div>
<div class="cell">内容2</div>
</div>
</div>
.table {
display: table;
width: 100%;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
border: 1px solid #ddd;
padding: 8px;
}
.header .cell {
background-color: #4CAF50;
color: white;
}
.row:nth-child(even) {
background-color: #f2f2f2;
}
使用CSS Grid布局创建表格

<div class="grid-table">
<div class="header">标题1</div>
<div class="header">标题2</div>
<div>内容1</div>
<div>内容2</div>
</div>
.grid-table {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1px;
}
.grid-table > div {
padding: 8px;
border: 1px solid #ddd;
}
.header {
background-color: #4CAF50;
color: white;
}
.grid-table > div:nth-child(4n+3),
.grid-table > div:nth-child(4n+4) {
background-color: #f2f2f2;
}
表格样式增强技巧
添加悬停效果
.styled-table tr:hover {
background-color: #ddd;
}
固定表头
.table-container {
height: 300px;
overflow-y: auto;
}
.styled-table thead th {
position: sticky;
top: 0;
}
响应式表格

@media screen and (max-width: 600px) {
.styled-table {
border: 0;
}
.styled-table thead {
display: none;
}
.styled-table tr {
display: block;
margin-bottom: 15px;
}
.styled-table td {
display: block;
text-align: right;
}
.styled-table td::before {
content: attr(data-label);
float: left;
font-weight: bold;
}
}
高级表格功能
斑马条纹效果
.styled-table tr:nth-child(odd) {
background-color: #f9f9f9;
}
.styled-table tr:nth-child(even) {
background-color: #ffffff;
}
单元格合并样式
.merged-cell {
grid-column: span 2;
text-align: center;
}
边框样式定制
.custom-border {
border: 2px double #333;
border-radius: 5px;
}
以上方法提供了从基础到高级的CSS表格制作方案,可根据具体需求选择合适的方式。原生表格标签适合数据展示,div模拟表格更灵活,CSS Grid则适合现代布局需求。






