css制作表格
CSS 制作表格的基本方法
使用 table 标签配合 CSS 可以创建样式丰富的表格。以下是一个基础示例:
<table class="styled-table">
<thead>
<tr>
<th>标题1</th>
<th>标题2</th>
</tr>
</thead>
<tbody>
<tr>
<td>内容1</td>
<td>内容2</td>
</tr>
</tbody>
</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 thead tr {
background-color: #009879;
color: #ffffff;
text-align: left;
}
.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 将表格转换为卡片布局:
@media screen and (max-width: 600px) {
.styled-table thead {
display: none;
}
.styled-table tr {
display: block;
margin-bottom: 15px;
border: 1px solid #ddd;
}
.styled-table td {
display: block;
text-align: right;
padding-left: 50%;
position: relative;
}
.styled-table td::before {
content: attr(data-label);
position: absolute;
left: 15px;
width: 45%;
padding-right: 10px;
font-weight: bold;
text-align: left;
}
}
HTML 需要为每个 td 添加 data-label 属性:

<td data-label="标题1">内容1</td>
表格悬停效果
增加交互效果提升用户体验:
.styled-table tbody tr:hover {
background-color: #e8f4fc;
cursor: pointer;
}
.styled-table tbody tr.active-row {
font-weight: bold;
color: #009879;
}
斑马条纹表格
使用 nth-child 选择器实现交替行颜色:

.styled-table tbody tr:nth-child(odd) {
background-color: #f9f9f9;
}
.styled-table tbody tr:nth-child(even) {
background-color: #ffffff;
}
固定表头表格
当表格内容较长时,固定表头方便浏览:
.styled-table {
position: relative;
}
.styled-table thead {
position: sticky;
top: 0;
z-index: 10;
}
需要为包含表格的容器设置高度和 overflow: auto:
.table-container {
max-height: 400px;
overflow: auto;
}
这些 CSS 技巧可以组合使用,根据实际需求调整样式参数。通过合理运用边框、背景色、阴影等属性,可以创建出既美观又功能完善的表格。






