html css制作表格
HTML 和 CSS 制作表格的方法
基础表格结构
使用 HTML 的 <table> 标签创建表格框架,包含 <tr>(行)、<th>(表头)和 <td>(单元格)标签。
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
<tr>
<td>张三</td>
<td>25</td>
</tr>
</table>
添加 CSS 样式
通过 CSS 控制表格边框、间距和颜色等样式属性。

table {
border-collapse: collapse; /* 合并边框 */
width: 100%;
}
th, td {
border: 1px solid #ddd; /* 单元格边框 */
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2; /* 表头背景色 */
}
响应式表格
针对小屏幕设备,通过 CSS 媒体查询调整表格布局。
@media screen and (max-width: 600px) {
table {
display: block;
overflow-x: auto; /* 横向滚动 */
}
}
斑马纹效果
使用 nth-child 选择器实现交替行颜色,增强可读性。

tr:nth-child(even) {
background-color: #f9f9f9;
}
悬停高亮
通过 :hover 伪类实现鼠标悬停时的高亮效果。
tr:hover {
background-color: #e9e9e9;
}
完整示例
结合 HTML 和 CSS 的完整表格代码示例:
<style>
table {
border-collapse: collapse;
width: 80%;
margin: 20px auto;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
tr:hover {
background-color: #ddd;
}
</style>
<table>
<tr>
<th>姓名</th>
<th>职业</th>
<th>城市</th>
</tr>
<tr>
<td>张三</td>
<td>设计师</td>
<td>北京</td>
</tr>
<tr>
<td>李四</td>
<td>开发员</td>
<td>上海</td>
</tr>
</table>
通过以上方法可以创建美观且功能完善的表格,根据实际需求调整样式属性和结构。






