You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让HTML表格的右侧滚动条不显示在表格内容中间?

表格滚动条位置异常修复方案

问题根源

单独给tbody设置display: block时,未同步给thead设置相同的块级显示规则,加上tbody上多余的float: right属性、表头表体未做列宽对齐,导致tbody实际渲染宽度未撑满整行,滚动条就会偏移到内容中间位置,而非表格最右边缘。

修复步骤

  • 删除table tbody样式中多余的float: right属性
  • 给table thead添加display: block规则,和表体保持一致的块级布局
  • 给th、td设置统一宽度规则,开启盒模型适配,避免表头表体列错位
  • 保持tbody宽度为100%,让滚动区域撑满表格全宽,滚动条自然贴靠最右侧

修正后完整代码

HTML代码

<table id="container" cellspacing="0">
     <thead>
         <tr>
             <th>Commands</th>
             <th>Aliases</th>
             <th>Description</th>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>help</td>
             <td>Help</td>
             <td>List all available commands on AnVolt with description</td>
         </tr>
         <tr>
             <td>clean</td>
             <td>Purge</td>
             <td>Clean total messages in current channel</td>
         </tr>
         <tr>
             <td>userinfo</td>
             <td>Profile</td>
             <td>Gives you information about specific users, default is your profile</td>
         </tr>
         <tr>
             <td>serverinfo</td>
             <td>GuildInfo</td>
             <td>Gives you information about current server/guild, such a member count</td>
         </tr>
     </tbody>
 </table>

注:原HTML中table标签里id属性后多余的逗号已删除,属于语法冗余。

CSS代码

table {
    border-collapse: collapse;
    box-sizing: border-box;
    box-shadow: 0 0 10px #000;
    text-align: left;
    overflow: hidden;
    width: 65%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    position: fixed;
    border-radius: 10px;
}

table thead {
    display: block;
    background-color: #000;
    color: #fff;
}

table th,
table td {
    padding: 16px 32px;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-size: 15px;
    font-weight: 700;
    width: 33.33%;
    box-sizing: border-box;
}

table tbody {
    display: block;
    height: 100px;
    overflow: auto;
    width: 100%;
}

调整后滚动条会固定在表格最右边缘,表头和表体列完全对齐。如果需要自定义各列宽度,只要同步修改对应th和td的宽度值即可。

内容的提问来源于stack exchange,提问作者Erle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 03:36:26