如何获取最右边的列以填充剩余空间?

Hub*_*bro 44 html css html-table

假设我有一个只有三个小列的表.如果我的屏幕左侧有一个狭窄,高大的桌子(示例),看起来不整洁且不平衡,所以我希望桌子能够覆盖页面的宽度.但是,当我将表格宽度设置为100%时,所有列都会被拉伸,所以现在我的数据在屏幕上分散得很薄,看起来也不整齐(例如).

我正在寻找的是一种解决方案,其中所有列的大小与表格相同width: auto,但最后一列填充了屏幕上的剩余空间.这就是Spotify所做的,例如:

Spotify的

无论如何,"用户"列将覆盖剩余宽度.是否有一种相对简单的方法来实现HTML表格和CSS?

Hub*_*bro 62

我找到了一个简单的解决方案:

table td:last-child {
    width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

结果:

截图

body {
    font: 12px "Sans serif";
}

table {
    width: 100%;

    background-color: #222222;
    color: white;
    border-collapse: collapse;
}

table th {
    padding: 10px;
    text-align: left;
}

table td {
    padding: 2px 10px;
}

table td:last-child {
    width: 100%;
}

table td:nth-child(odd), table th:nth-child(odd) {
    background-color: rgba(255, 255, 255, 0.05);
}

table tr:nth-child(even) {
    background-color: rgba(255, 255, 255, 0.05);
}

table tr:last-child td {
    padding-bottom: 10px;
}
Run Code Online (Sandbox Code Playgroud)
<table>
    <tr>
        <th>Product</th>
        <th>Cardinality</th>
        <th>Price per item</th>
    </tr>
    <tr>
        <td>Apple</td>
        <td>5</td>
        <td>$2</td>
    </tr>
    <tr>
        <td>Pear</td>
        <td>3</td>
        <td>$3</td>
    </tr>
    <tr>
        <td>Sausage</td>
        <td>10</td>
        <td>$0.5</td>
    </tr>
    <tr>
        <td>Pineapple</td>
        <td>2</td>
        <td>$8</td>
    </tr>
    <tr>
        <td>Tomato</td>
        <td>5</td>
        <td>$1</td>
    </tr>
    <tr>
        <td>Lightsaber</td>
        <td>2</td>
        <td>$99 999</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

这似乎适用于我目前的情况,但它看起来像在其他情况下会导致不必要的副作用.如果我遇到任何问题,我会编辑这个答案.

可能的副作用

  • 多字表格单元格将被包裹成多行,以使列尽可能窄.一种解决方案是white-space: nowrap在表格单元格上使用,但这会阻止包含大量文本的单元格.

  • 尝试用2个长单词填充产品,单词将折叠到下一行,你需要一个白色空间:nowrap; 每个td,检查我的答案 (4认同)

AzD*_*ign 17

如果这是你的意思:图像 然后我可以使用标准的html表结构与以下css实现:

table {
  width:auto;
}
td {
  white-space:nowrap;
}
td:last-child {
  width:100%;
}
Run Code Online (Sandbox Code Playgroud)

--EDIT:与你的jsfiddle一起工作


Chr*_*ald 10

将表格宽度设置为100%.在除最右边的列之外的所有列上设置宽度.最右边的列将展开以填充可用空间.

  • 这部分怎么样:"......如果表格是'width:auto` ...",那么所有列的大小都与它们的大小相同.如果我每次数据更改时都要手动编辑列的大小......我将不得不辞掉工作 (3认同)