我需要为内容超过某个阈值的表格单元格添加省略号。
假设我有这个:
<tr>
<td><a href="#">Fooooooooooooooooooooo</a></td>
<td><a href="#">b</a></td>
<td><a href="#">c</a></td>
<td><a href="#">d</a></td>
</tr>
目前我正在 CSS 中进行设置:
table tr td a,
table tr th a {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
table tr th:first-child:nth-last-child(4),
table tr th:first-child:nth-last-child(4) ~ th,
table tr td:first-child:nth-last-child(4),
table tr td:first-child:nth-last-child(4) ~ td {
max-width: 25%;
}
但它不起作用 = 表格单元格不限于可用宽度的 25%。
问题:
是否可以在 CSS 中设置表格单元格宽度?或者我可以只定位表格单元格的内容吗?
最佳答案
通常情况下,表格的单元格采用定义的 css 宽度,但它会增长以适应其内联/ block 内容,忽略定义的规则。
一个可能的解决方案是从正常流中移除 anchor ,将其设置为 position: absolute;
并使其全宽。这将阻止单元格扩展,并将 anchor 限制为可用单元格宽度的 100%
。
记得将表格单元格设置为 position: relative
以便它充当容器
还要记住设置表格的宽度,否则 25%
将毫无意义
table tr td a,
table tr th a {
position: absolute;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
table {
width: 200px;
}
table tr th:first-child:nth-last-child(4),
table tr th:first-child:nth-last-child(4) ~ th,
table tr td:first-child:nth-last-child(4),
table tr td:first-child:nth-last-child(4) ~ td {
max-width: 25%;
position: relative;
}
<table>
<tr>
<td><a href="#">Fooooooooooooooooooooo</a></td>
<td><a href="#">b</a></td>
<td><a href="#">c</a></td>
<td><a href="#">d</a></td>
</tr>
</table>
关于html - 我可以通过 CSS 设置表格单元格元素的宽度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26803611/