参考资料

  1. html表格标签详细说明以及案例
  2. HTML使用表格 布局
  3. HTML高度与宽度设置 Iframe
  4. HTML 用于联系信息的
  5. HTML 内联式
  6. HTML id 属性在 JavaScript 中的使用
  7. 如何添加按钮的过渡动画效果?
  8. HTML 表格的嵌套

HTML 表格格式化

基本介绍

HTML表格用于在网页上展示行列数据,由<table>标签定义,包含行(<tr>)、表头单元格(<th>)和数据单元格(<td>)。

主要标签

  1. <table> - 定义表格

  2. <tr> - 定义表格行

  3. <th> - 定义表头单元格

  4. <td> - 定义标准单元格

  5. <caption> - 定义表格标题

  6. <thead> - 定义表头区域

  7. <tbody> - 定义表格主体

  8. <tfoot> - 定义表格页脚

基本用法

<table>
  <caption>学生成绩表</caption>
  <thead>
    <tr>
      <th>姓名</th>
      <th>数学</th>
      <th>语文</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>张三</td>
      <td>90</td>
      <td>85</td>
    </tr>
    <tr>
      <td>李四</td>
      <td>78</td>
      <td>92</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>平均分</td>
      <td>84</td>
      <td>88.5</td>
    </tr>
  </tfoot>
</table>

常用属性

  1. border - 设置表格边框宽度

  2. cellpadding - 设置单元格内边距

  3. cellspacing - 设置单元格间距

  4. colspan - 单元格横跨列数

  5. rowspan - 单元格纵跨行数

CSS扩展样式

/* 基本表格样式 */
table {
  width: 100%;
  border-collapse: collapse; /* 合并边框 */
  margin: 20px 0;
}

/* 单元格样式 */
th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

/* 表头样式 */
th {
  background-color: #f2f2f2;
  font-weight: bold;
}

/* 斑马条纹效果 */
tr:nth-child(even) {
  background-color: #f9f9f9;
}

/* 悬停效果 */
tr:hover {
  background-color: #f1f1f1;
}

/* 响应式表格 */
@media screen and (max-width: 600px) {
  table {
    border: 0;
  }
  table thead {
    display: none;
  }
  table tr {
    margin-bottom: 10px;
    display: block;
    border: 1px solid #ddd;
  }
  table td {
    display: block;
    text-align: right;
    border-bottom: 1px solid #ddd;
  }
  table td:before {
    content: attr(data-label);
    float: left;
    font-weight: bold;
  }
}

高级功能实例

合并单元格

<table border="1">
  <tr>
    <th rowspan="2">姓名</th>
    <th colspan="2">成绩</th>
  </tr>
  <tr>
    <th>数学</th>
    <th>语文</th>
  </tr>
  <tr>
    <td>张三</td>
    <td>90</td>
    <td>85</td>
  </tr>
</table>

固定表头滚动表格

.table-container {
  height: 300px;
  overflow: auto;
}
table thead th {
  position: sticky;
  top: 0;
  background: #f2f2f2;
}