table表头固定只让内容滚动

纯css实现表头固定,只tbody滚动 需要用到粘性固定属性 – position:sticky

  • position:sticky 用法:默认情况下,其表现为relative,在视窗与设置了该属性的元素之间,达到或超过其预设的 top、bottom、left、right,本属性会转变成 fixed,使 sticky 固定。
  • html结构:table外面需要包一层div
<div class="table-box">
    <table>
      <thead>
        <tr>
          <th class="text-center">序号</th>
          <th class="text-center">名称</th>
          <th class="text-center">电话</th>
          <th class="text-center">备注</th>
          <th class="text-center">录入时间</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in [1,2,3]">
          <td class="text-center"></td>
          <td class="text-center"></td>
          <td class="text-center"></td>
          <td class="text-center"></td>
          <td class="text-center"></td>
        </tr>
      </tbody>
    </table>
  </div>
  • css是最关键的,需要分别对table自身和其父便签设置样式
// table父标签: 需要设置固定高度
  .table-box {
    height: 500px;
    overflow-y: auto;
    border: 1px solid #ddd;
  } 

// table表格样式
  table {
    width: 100%;
    table-layout: fixed;
    
    thead th {
      position: sticky;
      top: -1px;
      z-index: 10;
    }
  }