使用css制作表格
使用HTML和CSS创建表格
使用HTML的<table>标签结合CSS可以创建各种样式的表格。以下是一个基础示例:
<table class="custom-table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
</tr>
<tr>
<td>Row 2 Cell 1</td>
<td>Row 2 Cell 2</td>
</tr>
</tbody>
</table>
基础表格样式
通过CSS可以调整表格的边框、间距和颜色:
.custom-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.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: #e9e9e9;
}
响应式表格设计
对于移动设备,可以通过媒体查询使表格水平滚动:
@media screen and (max-width: 600px) {
.responsive-table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
}
斑马条纹效果
使用CSS的:nth-child()选择器创建交替行颜色:

.striped-table tr:nth-child(odd) {
background-color: #f2f2f2;
}
.striped-table tr:nth-child(even) {
background-color: #ffffff;
}
表格边框样式
自定义表格边框样式和圆角:
.rounded-table {
border: 1px solid #ddd;
border-radius: 5px;
overflow: hidden;
}
.rounded-table th, .rounded-table td {
border: 1px solid #ddd;
}
表格单元格对齐
控制表格内容的对齐方式:
.align-center td {
text-align: center;
vertical-align: middle;
}
.align-right td {
text-align: right;
}
表格间距和填充
调整表格单元格的内边距和间距:

.spacious-table td {
padding: 15px;
}
.separated-table {
border-spacing: 10px;
}
表格标题固定
创建固定表头的滚动表格:
<div class="scrollable-table-container">
<table class="fixed-header-table">
<!-- 表格内容 -->
</table>
</div>
.scrollable-table-container {
height: 300px;
overflow-y: auto;
}
.fixed-header-table thead th {
position: sticky;
top: 0;
background: white;
z-index: 10;
}
表格边框合并与分离
选择边框合并或分离模式:
.collapsed-table {
border-collapse: collapse;
}
.separated-table {
border-collapse: separate;
border-spacing: 5px;
}
高级表格样式
创建更复杂的表格样式,如悬停高亮:
.highlight-table td {
transition: background-color 0.3s;
}
.highlight-table td:hover {
background-color: #ffeb3b;
}
这些方法提供了从基础到高级的表格样式定制选项,可以根据具体需求组合使用或进一步扩展。






