表元素内两列之间的相等间距

问题描述 投票:1回答:4

table {
width:100%;
}
td {
padding:15px;
}
<table>
  <tr>
    <td>100</td>
    <td>20A long text</td>
    <td>300</td>
    <td>300</td>

  </tr>
  <tr>
    <td>400</td>
    <td>500</td>
    <td>600</td>
    <td>300</td>

  </tr>
</table>

细胞的含量可以是变化的长度,细胞宽度将根据含量而定。它必须看起来像这样

| --- Text1 --- | ---很长的文字--- | ---文字3 --- |

但这就是现在的样子

| --Text1-- | -----一个很长的文本----- | - 文本3-- |

重申一下,我不期望单元格宽度相等,但列之间的间距相等。

html css html-table multiple-columns
4个回答
2
投票

不幸的是,我不知道在纯CSS中这样做的方法。 作为一种变通方法,您可以使用JavaScript计算每个表格单元格所需的宽度,以达到100%的宽度。

这是怎么开始的?请注意,我更改了CSS以将水平填充设置为0(这是必要的,否则您将必须在JS计算中合并计算的填充);我给了细胞边界(这不是必需的,但它更好地证明了所需的结果)。

let tbl = document.getElementById('tbl');
tbl.style.width = 'auto';
let extraSpace = document.body.clientWidth - tbl.offsetWidth;
let cols = tbl.rows[0].cells.length;
for (i = 0; i<cols; ++i) {
  let padding = Math.round(extraSpace/(cols-i));
  let cell = tbl.rows[0].cells[i];
  cell.style.width = (cell.clientWidth + padding) + 'px';
  extraSpace -= padding;
}
table {
  width: 100%;
}

td {
  padding: 15px 0;
  text-align: center;
  border:1px dotted gray;
}
<table id="tbl">
  <tr>
    <td>100</td>
    <td>20A long text</td>
    <td>300</td>
    <td>300</td>
  </tr>
  <tr>
    <td>400</td>
    <td>500</td>
    <td>600</td>
    <td>300</td>
  </tr>
</table>

0
投票

如果你删除width:100%,列将拉伸以适合内容,其间填充相等的15px。此时,100%的宽度导致表格自动重新分配可用空间以填充屏幕的宽度。


0
投票

使用CSS,您可以为padding-leftpadding-right元素设置<td><th>,以设置列之间的间距。

td, th {
  padding-left: 15px;
  padding-right: 15px;
}
<table border="1">
  <tr>
    <th>1st cell</th>
    <th>2nd cell</th>
    <th>3rd cell</th>
  </tr>
  <tr>
    <td>1st cell content</td>
    <td>2nd cell content</td>
    <td>3rd cell content</td>
  </tr>
</table>

-1
投票

请为下一个问题提供您的代码。 你可以添加CSS属性table-layout:fixed;到表标签 fixed属性:设置固定的表格布局算法。表格和列宽度由table和col的宽度或第一行单元格的宽度设置。其他行中的单元格不会影响列宽。如果第一行上没有宽度,则无论单元格内部的内容如何,​​列宽均在表格中平均分配 此外,您可以为单元格设置固定填充(左侧和右侧),以便具有左右固定的空间 这是一个例子

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">

        .tab-cell {
            padding-left: 20px;
            padding-right:  20px;
        }

    </style>
</head>
<body>
    <table style="table-layout: fixed; text-align: center;" border="1">
        <tr>
            <th class = "tab-cell">Column A</th>
            <th class = "tab-cell">Column B</th>
            <th class = "tab-cell">Column C</th>
        </tr>
        <tr>
            <th class = "tab-cell">some content</th>
            <th class = "tab-cell">some looooooooooooooooooooooooooooooooong content</th>
            <th class = "tab-cell">some content</th>
        </tr>
    </table>
</body>
</html>


Result

enter image description here
Hope it helps.
Hele
© www.soinside.com 2019 - 2024. All rights reserved.