【问题标题】:How to split extra space evenly between columns when setting width on table在表格上设置宽度时如何在列之间平均分配额外的空间
【发布时间】:2021-05-23 03:18:19
【问题描述】:

我一直在寻找这个问题的答案很长时间,但从未看到答案。

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

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

编辑:我设法使 sn-p 工作,如您所见,每个单元格右侧的空白区域从不一样,看起来很奇怪

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>

【问题讨论】:

  • 那么,您希望表格单元格的宽度相同,并且分布均匀?
  • 不完全是,我不希望它们具有相同的宽度,但我希望它们右侧的空白每次都相同,以便它们最终加起来等于我设置的宽度。使用代码 sn-p 会更清楚,但我不知道为什么它在这里不起作用
  • 尝试将 padding-right 设置为固定值“40px”或类似“10%”的百分比
  • 是的,我发现这可行,但我真正想要的是达到一个特定的宽度,所以如果我的 变得更长,因为里面的文本发生了变化,最终的长度将不是我想要的

标签: css html-table


【解决方案1】:

如果您正在寻找单元格内容右侧的相等间距,我认为仅使用 HTML 和 CSS 是不可能的。您可能需要使用 JavaScript 来获得您正在寻找的结果。我已经为你拼凑了这个“弗兰肯斯坦”剧本。我怀疑它是最干净的代码或最实用的代码,但它似乎可以满足您的需求。如果这对您不起作用,我会研究 Sass 或完全放弃表格布局并使用 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>

【讨论】:

    【解决方案2】:

    我认为您也必须为&lt;tr&gt;&lt;td&gt; 提供固定宽度。

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签