【问题标题】:How to keep the column width in an HTML table equal for all columns based on the widest column如何根据最宽列保持 HTML 表格中所有列的列宽相等
【发布时间】:2012-11-10 23:08:29
【问题描述】:

我看到很多关于列宽的问题,但我无法找到与我完全一样的场景的答案。

这是我的桌子:

<table>
    <tr>
        <td colspan="3">Title goes here</td>
        <td>A</td>
        <td class="right">B</td>
    </tr>

    <tr>
        <td rowspan="3">C</td>
        <td>D</td>
        <td>E</td>
        <td>F</td>
        <td class="right">G</td>
    </tr>

    <tr>
        <td>H</td>
        <td colspan="2" class="center">I</td>
        <td rowspan="2" class="right">J</td>
    </tr>

    <tr>
        <td>K</td>
        <td>L</td>
        <td>M</td>
    </tr>

    <tr>
        <td class="right">N</td>
        <td colspan="4" class="center">O</td>
    </tr>
</table>

这是我的 CSS:

<style>
    table 
    {
        table-layout: fixed;

    }

    table, td 
    {
        border: 1px solid;
    }

    .right 
    {
        text-align:right;
        vertical-align:bottom;
    }
    .center 
    {
        text-align: center;
    }
</style>

我想要实现的是所有五列在最宽的基础上具有相同的宽度。我的想法是我不知道标题会有多大。我知道我可以为表格设置固定宽度(例如 200 像素或 100%),但我不想这样做。我希望列的宽度和表格的宽度随着标题的扩展而扩展。如您所见,标题跨越三列。

【问题讨论】:

    标签: html html-table column-width


    【解决方案1】:

    恐怕这不能在 HTML 中完成,即使在 CSS 的帮助下。您还需要一些脚本:在浏览器格式化表格后处理表格的脚本,找出最宽的列,并将所有列设置为该宽度。假设您的 table 元素具有 id=t,则以下纯 JavaScript 代码可以完成这项工作:

    <script>
    window.onload = function () {
    var tbl = document.getElementById("t");
    var row = tbl.rows[0];
    var maxWidth = 1;
    for ( var i = 0; i < row.childNodes.length; i++ ) {
      var width = row.childNodes[i].offsetWidth;
      if(width > maxWidth) { maxWidth = width; } 
      }
    for ( var i = 0; i < row.childNodes.length; i++ ) {
      row.childNodes[i].style.width = maxWidth + "px"; 
      }
    }
    </script>
    

    【讨论】:

    • 非常感谢,我会试试的。
    猜你喜欢
    • 2010-10-08
    • 2018-02-25
    • 1970-01-01
    • 2021-06-18
    • 2019-05-20
    • 2020-06-21
    • 2015-07-29
    • 2013-04-27
    • 2022-07-27
    相关资源
    最近更新 更多