html - 如何让最右边的列填充剩余空间?

标签 html css html-table

假设我有一个只有三个小列的表。一张又窄又高的 table 紧挨着我的屏幕左侧 ( example ) 看起来不整洁且不平衡,所以我希望 table 能覆盖页面的宽度。然而,当我将表格宽度设置为 100% 时,所有列也都被拉伸(stretch),所以现在我的数据在屏幕上稀疏地分布,看起来也很凌乱 (example)。

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

Spotify

无论如何,“用户”列将覆盖剩余的宽度。有没有一种相对简单的方法可以使用 HTML 表格和 CSS 实现这一点?

最佳答案

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

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

结果:

Screenshot

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;
}
<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>

这似乎适用于我当前的情况,但它看起来可能会在其他情况下导致不必要的副作用。如果我偶然发现任何问题,我会编辑这个答案。

可能的副作用

  • 多字表格单元格将换行成多行,以使列尽可能窄。一种解决方案是在表格单元格上使用 white-space: nowrap,但这会阻碍包含大量文本的单元格在它们应该换行的时候换行。

关于html - 如何让最右边的列填充剩余空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137757/

相关文章:

javascript - 拖动和交换列表元素

javascript - 将 p 标签值限制为一行并在最后一个完整单词后中断

javascript - 当用作等宽字体时,使来自非等宽字体的替换字符以正确的宽度显示

html - 内联样式的表格单元格向下移动一个像素

php - codeIgniter View 文件中表格格式的特定方式的数组表示?

html - 转换元素内的 CSS 不透明动画

python - Django - 将 css 类添加到管理中的输入字段

html - 放大或缩小时我的内容错位了

html - 如何使用填充颜色覆盖 html td?

Javascript - ReactJS - 以 ReadableStream 作为源显示图像