如何获得最右边的列来填充剩余的空间?

假设我有一个只有三列的表。它看起来不整洁和不平衡有一个狭窄的,高的桌子拥抱我的屏幕左侧(例子) ,所以我希望表覆盖的宽度的页面。但是,当我将表宽设置为100% 时,所有的列也都被拉长了,所以现在我的数据在屏幕上分散得很稀疏,看起来也很不整洁(例子)。

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

Spotify

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

63556 次浏览

If this is what you meant: image

Then I can achieve that using standard html table structure with the following css:

table {
width:auto;
}
td {
white-space:nowrap;
}
td:last-child {
width:100%;
}

--EDIT : work with your jsfiddle

I have found a simple solution:

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

Result:

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>

This appears to work in my current scenario, but it looks like something that can cause unwanted side effects in other situations. If I stumble across any, I'll edit this answer.

Possible side effects

  • Multi-word table cells will be wrapped into multiple lines to keep the column as narrow as possible. One solution is to use white-space: nowrap on the table cells, but that will hinder cells with lots of text from wrapping when they should.