你如何制作一个从不换行并且自动宽度的表格列?
我需要创建一个两列全宽表,其中:
- 第 1 列在需要时换行
- 第 2 列永远不会包装和填充任何空白空间
在此处查看视觉示例:
我在弄清楚这一点时遇到了很多麻烦......这就是我要做的事情:
table {
width: 100%;
}
.col-2 {
white-space: nowrap;
width: 60%;
text-align: right;
}
/* Below is arbitrary example CSS, not part of solution */
.container {
width: 250px;
}
td {
background: lightblue;
}
<h4>Example A</h4>
<div>
<table>
<tr>
<td class='col-1'>Not much text</td>
<td class='col-2'>Column 2</td>
</tr>
</table>
<h4>Example B</h2>
<table>
<tr>
<td class='col-1'>This has a lot of text that wraps</td>
<td class='col-2'>Column 2</td>
</tr>
</table>
</div>
回答
CSS 网格应该这样做:
div {
display: grid;
width: 250px;
grid-gap: 2px;
grid-template-columns: auto 1fr;
}
.col-2 {
white-space: nowrap;
text-align: right;
}
p {
background: hotpink;
margin: 0;
}
<h4>Example A</h4>
<div>
<p class='col-1'>Not much text</p>
<p class='col-2'>Column 2</p>
<p class='col-1'>row2</p>
<p class='col-2'>Column 2</p>
</div>
<h4>Example B</h4>
<div>
<p class='col-1'>This has a lot of text that wraps</p>
<p class='col-2'>Column 2</p>
<p class='col-1'>row2</p>
<p class='col-2'>Column 2</p>
</div>