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

如何让标题居中对齐在表格正上方并缩小二者间距?

解决方案

要实现标题居中在表格正上方、缩小两者间距的效果,只需对代码做3处关键修改:

  • 用容器绑定标题与表格:新增容器包裹标题和表格,通过容器控制整体右对齐,确保标题始终在表格正上方
  • 调整标题对齐方式:将标题的右对齐改为居中对齐
  • 缩小间距:把表格的上外边距从130px改为合适的小数值

修改后的完整代码

<body>
    <style type="text/css">
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:13px 14px;word-break:normal;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:13px 14px;word-break:normal;}
    .tg .tg-l183{background-color:#96fffb;border-color:inherit;font-family:"Courier New", Courier, monospace !important;font-size:16px;
      font-weight:bold;text-align:left;vertical-align:top}
    .tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
    /* 新增容器样式 */
    .table-container {
        text-align: right; /* 让整个容器右对齐 */
        margin-left: 10px; /* 保留原表格的左外边距 */
    }
    </style>

    <header>
        <h1>DRAINAGE PLAN</h1>
        <h2>Drainge plan for Cypresshead</h2>
    </header>
    <!-- 用容器包裹标题和表格 -->
    <div class="table-container">
        <h2 style="text-align:center">Pump Monitor</h2>
        <table style="margin-top:15px;" class="tg">
        <thead>
          <tr>
            <th class="tg-l183">PUMP</th>
            <th class="tg-l183">START-TIME</th>
            <th class="tg-l183">DURATION(mins)</th>
            <th class="tg-l183">PUMPED(gals)</th>
            <th class="tg-l183">CYCLE</th>
            <th class="tg-l183">STATUS</th>
          </tr>
        </thead>
        </table>
    </div>
</body>

关键修改说明

  1. 容器作用:.table-container的text-align:right让表格和标题整体靠右,同时内部元素可独立设置对齐方式,确保标题在表格正上方居中
  2. 标题调整:把h2的text-align:right改成text-align:center,让标题在容器内居中,正好对应表格的宽度范围
  3. 间距调整:将表格的margin-top:130px改为margin-top:15px(可根据视觉需求微调数值),直接缩小标题与表格的间距

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:55:25