css 制作表格
CSS 制作表格的方法
使用CSS创建表格可以通过多种方式实现,以下是几种常见的方法:
使用HTML表格标签结合CSS样式
通过HTML的<table>、<tr>、<td>等标签创建表格结构,再用CSS美化样式。

<table class="styled-table">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
.styled-table {
width: 100%;
border-collapse: collapse;
margin: 25px 0;
font-size: 0.9em;
font-family: sans-serif;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}
.styled-table th,
.styled-table td {
padding: 12px 15px;
}
.styled-table tbody tr {
border-bottom: 1px solid #dddddd;
}
.styled-table tbody tr:nth-of-type(even) {
background-color: #f3f3f3;
}
.styled-table tbody tr:last-of-type {
border-bottom: 2px solid #009879;
}
使用CSS Grid布局
通过CSS Grid布局模拟表格效果,适合需要更灵活布局的场景。

<div class="grid-table">
<div class="header">Header 1</div>
<div class="header">Header 2</div>
<div class="cell">Data 1</div>
<div class="cell">Data 2</div>
</div>
.grid-table {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1px;
background-color: #ddd;
}
.grid-table > div {
padding: 12px 15px;
background: white;
}
.header {
font-weight: bold;
}
使用Flexbox布局
Flexbox也可以用来创建表格布局,特别适合响应式设计。
<div class="flex-table">
<div class="row">
<div class="cell header">Header 1</div>
<div class="cell header">Header 2</div>
</div>
<div class="row">
<div class="cell">Data 1</div>
<div class="cell">Data 2</div>
</div>
</div>
.flex-table {
display: flex;
flex-direction: column;
border: 1px solid #ddd;
}
.row {
display: flex;
}
.cell {
flex: 1;
padding: 12px 15px;
border: 1px solid #ddd;
}
.header {
font-weight: bold;
background-color: #f3f3f3;
}
响应式表格设计
对于移动设备,可以通过媒体查询使表格在小屏幕上显示为堆叠布局。
@media screen and (max-width: 600px) {
table.responsive-table {
width: 100%;
}
table.responsive-table thead {
display: none;
}
table.responsive-table tr {
margin-bottom: 15px;
display: block;
border: 1px solid #ddd;
}
table.responsive-table td {
display: block;
text-align: right;
padding-left: 50%;
position: relative;
}
table.responsive-table td::before {
content: attr(data-label);
position: absolute;
left: 15px;
font-weight: bold;
}
}
以上方法可以根据项目需求选择使用,传统HTML表格适合数据展示,CSS Grid和Flexbox提供更灵活的布局选项,响应式设计确保在不同设备上都能良好显示。






