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

Firefox中tbody使用calc设置高度不生效的问题及解决方法

问题描述

我创建了一个带表头和固定高度内容的表格,在Chrome、Edge、IE11浏览器中运行正常,但Firefox中tbody的高度样式不生效。

表格结构

<table>
  <thead>
    <tr>
      <th>...</th>
      <th>...</th>
      <th>...</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    ...
  </tbody>
</table>

表格外层包裹了一个宽度100%、高度400px的div容器,对应CSS代码如下:

table {
  width: 100%;
  height: 100%;
}

thead {
  width: 100%;
  height: 30px;
}

tbody {
  width: 100%;
  height: calc(100% - 30px); // <--- Firefox下无法正常生效
}

如果把tbody的height设为固定值(比如200px)就能解决问题,暂时没定位到错误根源,希望有相关经验的开发者提供思路。

解决方案

在表格组件的构造函数中添加如下代码判断浏览器类型:

const userAgent = (navigator && navigator.userAgent || '').toLowerCase();
this.isFirefoxOrIE = !!userAgent.match(/(?:firefox|fxios)\/(\d+)/) || !!userAgent.match(/(?:msie |trident.+?; rv:)(\d+)/);

随后编写函数动态设置tbody高度:

public getTableBodyHeight(): string {
        return (this.isFirefoxOrIE) ? `${document.getElementsByClassName('my-container')[0].parentElement.parentElement.clientHeight - 41}px !important` : 'calc(100% - 31px)';
    }

最后在HTML中绑定样式即可生效:

<tbody [style.height]="getTableBodyHeight()">
   ...
</tbody>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:21:00