在 table 上设置宽度时如何在列之间平均拆分额外的 space

How to split extra space evenly between columns when setting width on table

我一直在寻找这个问题的答案,但一直没有看到答案。

我正在 HTML 中制作一个 table 并将其设置为特定宽度(通常它会占据所有 space)。它比它必须的要大,所以在不同的列之间有额外的 space 拆分。问题是它是按单元格的宽度按比例分割的,而不是均匀的,这看起来很奇怪。
例如,对于 120px 的宽度,你会得到一个 10px 的大列,左边有 20px 的额外 space,而不是 30px 的大列,左边有 60px 的额外 space。
而不是 10 + 20 + 30 + 60,我更喜欢 10 + 40 + 30 + 40,但我看不出有什么办法。在我看来,这可能是 table 布局,但唯一的其他选项是“固定”,它为整个列提供固定大小,而不是额外的 space(提供 10 + 50 + 30 + 30)

我希望我能把我的问题说清楚,抱歉英语不好

编辑:我设法使代码片段起作用,如您所见,每个单元格右侧的白色 space 从来都不一样,看起来很奇怪

table{
    width: 600px;
    border-collapse: collapse;
}
.fixed{
    table-layout: fixed;
}
td{
    border: 1px solid black;
}
<table>
    <tr>
        <td>Short</td>
        <td>A much much much much longer cell</td>
        <td>A</td>
    </tr>
</table>

<table class="fixed">
    <tr>
        <td>Short</td>
        <td>A much much much much longer cell</td>
        <td>A</td>
    </tr>
</table>

我认为您也必须为 <tr><td> 提供固定宽度。

如果您正在寻找单元格内容右侧的相等间距,我认为单独使用 HTML 和 CSS 是不可能的。您可能需要使用 JavaScript 来获得您要查找的结果。我已经为你拼凑了这个“科学怪人”的剧本。我怀疑它是最干净的代码还是最实用的代码,但它似乎可以满足您的需求。如果这对您不起作用,我会研究 Sass 或完全放弃 table 布局并使用 div。

const table = document.getElementById('myTable'); // Select Table
const width = table.clientWidth; // Record Fixed Width

table.style.width = "auto"; // Remove Table Width (I can't get this to work without removing the table width).

let length = 0;
let padding = 0;

const row = table.rows[0]; // Select First Row
const cols = row.children; // Select Each Cell in First Row

[].forEach.call(cols, function(col) {
    length += col.clientWidth; // Measure Cell Content
});

// Calculate Padding
if (width >= length) {
    padding = (width - length) / cols.length;
} else {
    // If Content Length is >= Table Width, the Default to Table Width (No Padding).
    table.style.width = `${width}px`;
}

// Add Padding to Each Cell in Table
const rows = table.rows;
    [].forEach.call(rows, function(row) {
    const cells = row.children;

    [].forEach.call(cells, function(cell) {
        cell.style.paddingRight = `${padding}px`
    }); 
});
table {
    width: 500px;
    border-collapse: collapse;
}

td { border: 1px solid black; }
<table id="myTable">
    <tr>
        <td>Stuff</td>
        <td>A lot more stuff</td>
        <td>Some stuff</td>
    </tr>
    <tr>
        <td>Stuff</td>
        <td>A lot more stuff</td>
        <td>Some stuff</td>
    </tr>
        <tr>
        <td>Some Stuff</td>
        <td>Fun stuff that I like</td>
        <td>Some stuff</td>
    </tr>
</table>