网页表格制作css代码
基础表格样式
使用CSS为HTML表格添加基础样式,包括边框、间距和背景色。以下代码适用于大多数简单表格场景:
<style>
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
font-family: Arial, sans-serif;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #f2f2f2;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f1f1f1;
}
</style>
响应式表格设计
对于移动设备友好的响应式表格,当屏幕尺寸较小时转为垂直布局:
@media screen and (max-width: 600px) {
table {
border: 0;
}
table thead {
display: none;
}
table tr {
border-bottom: 2px solid #ddd;
display: block;
margin-bottom: 15px;
}
table td {
border-bottom: 1px dotted #ccc;
display: block;
text-align: right;
padding-left: 50%;
position: relative;
}
table td::before {
content: attr(data-label);
position: absolute;
left: 10px;
font-weight: bold;
}
}
斑马条纹效果
创建交替行颜色的表格,增强可读性:

table.striped {
border: none;
}
table.striped tr:nth-child(odd) {
background-color: #f8f8f8;
}
table.striped tr:nth-child(even) {
background-color: #ffffff;
}
table.striped th {
background-color: #4CAF50;
color: white;
}
table.striped td {
border-bottom: 1px solid #ddd;
}
悬停高亮效果
为表格行添加悬停交互效果,提升用户体验:
table.hover-effect tr {
transition: background-color 0.3s ease;
}
table.hover-effect tr:hover {
background-color: #e3f2fd;
cursor: pointer;
}
table.hover-effect th {
background-color: #2196F3;
color: white;
}
table.hover-effect td {
border-bottom: 1px solid #ddd;
padding: 12px 15px;
}
紧凑型表格
适合需要显示大量数据的紧凑布局:

table.condensed {
font-size: 0.9em;
}
table.condensed th,
table.condensed td {
padding: 6px 8px;
}
table.condensed th {
background-color: #555;
color: white;
}
table.condensed tr:nth-child(even) {
background-color: #f5f5f5;
}
圆角边框表格
为表格添加现代风格的圆角设计:
table.rounded {
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
table.rounded th:first-child {
border-top-left-radius: 8px;
}
table.rounded th:last-child {
border-top-right-radius: 8px;
}
table.rounded tr:last-child td:first-child {
border-bottom-left-radius: 8px;
}
table.rounded tr:last-child td:last-child {
border-bottom-right-radius: 8px;
}
固定表头表格
长表格滚动时保持表头固定:
table.fixed-header {
position: relative;
}
table.fixed-header thead {
position: sticky;
top: 0;
z-index: 10;
}
table.fixed-header tbody {
display: block;
overflow-y: auto;
max-height: 400px;
}
table.fixed-header th,
table.fixed-header td {
width: auto;
}






