table表头固定只让内容滚动

本文介绍了如何使用CSS中的position:sticky属性来实现表格中表头固定,tbody部分滚动的效果。通过设置table外层div的高度并启用overflow-y:auto,以及对thead的th应用position:sticky和top:-1px,可以创建一个动态的表头,当tbody滚动时,表头始终保持可见。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

纯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;
    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值