问题描述
假设我有一个只有三个小栏目的表格。它看起来不整洁,不平衡,有一个狭窄,高的桌子拥抱在屏幕的左侧(),所以我想让表格覆盖页面的宽度。但是,当我将表宽度设置为100%时,所有的列也被拉伸,所以现在我的数据在屏幕上很薄,这也看起来不整洁()。
Say I have a table with only three small columns. It looks untidy and unbalanced to have a narrow, tall table hugging the left side of my screen (example), so I'd like the table to cover the width of the page. However, when I set the table width to 100%, all the columns are stretched out as well, so now my data is spread thinly across the screen, which also looks untidy (example).
我要找的是一个解决方案,尺寸,如果表是 width:auto
,但最后一列将填充屏幕上的剩余空间。这是Spotify的功能,例如:
What I'm looking for is a solution where all the columns have the same size as they would have had if the table was width: auto
, but the final column fills the remaining space on the screen. This is what Spotify does, for example:
用户列将覆盖剩余宽度,无论是什么。
The "User" column will cover the remaining width, no matter what. Is there a relatively simple way of achieving this with HTML tables and CSS?
推荐答案
我找到了一个简单的解决方案:
I have found a simple solution:
table td:last-child {
width: 100%;
}
结果:
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.
- 多字表单元格将被包装成多行,以使列尽可能窄。一个解决方案是在表格单元格上使用
white-space:nowrap
,但这将阻止具有大量文本的单元格在它们应该包装的时候。
- 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.
这篇关于如何获取最右边的列以填充剩余空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!