css样式制作表格
CSS 制作表格的基本方法
使用 table、tr、td 等 HTML 标签结合 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: 20px 0;
}
.styled-table th, .styled-table td {
padding: 12px 15px;
text-align: left;
border: 1px solid #ddd;
}
.styled-table th {
background-color: #f2f2f2;
font-weight: bold;
}
.styled-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.styled-table tr:hover {
background-color: #f1f1f1;
}
响应式表格设计
对于移动设备,可以通过媒体查询调整表格布局:

@media screen and (max-width: 600px) {
.styled-table {
display: block;
}
.styled-table thead, .styled-table tbody, .styled-table th,
.styled-table td, .styled-table tr {
display: block;
}
.styled-table thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
.styled-table tr {
margin-bottom: 15px;
}
.styled-table td {
border: none;
position: relative;
padding-left: 50%;
}
.styled-table td:before {
position: absolute;
left: 6px;
content: attr(data-label);
font-weight: bold;
}
}
表格样式进阶技巧
添加圆角边框和阴影效果:

.styled-table {
border-radius: 8px;
overflow: hidden;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
.styled-table th:first-child {
border-top-left-radius: 8px;
}
.styled-table th:last-child {
border-top-right-radius: 8px;
}
使用 CSS 变量实现主题切换:
:root {
--table-header-bg: #4CAF50;
--table-header-color: white;
--table-row-hover: #e8f5e9;
}
.styled-table th {
background-color: var(--table-header-bg);
color: var(--table-header-color);
}
.styled-table tr:hover {
background-color: var(--table-row-hover);
}
固定表头和列的实现
对于大型表格,可以固定表头和首列:
.table-container {
height: 400px;
overflow: auto;
}
.sticky-header thead th {
position: sticky;
top: 0;
z-index: 10;
}
.sticky-first-col td:first-child,
.sticky-first-col th:first-child {
position: sticky;
left: 0;
z-index: 5;
background: white;
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}
这些方法可以根据实际需求组合使用,创建出功能完善且美观的表格布局。






