我有一个使用100%区域宽度的表,并且它具有带有溢出的TD,我需要的是在文本太长时使他们的文本省略号。
我可以使用固定的TD尺寸进行操作,但是我需要将它们相对于内容
进行。这个问题是在3年前提出的:CSS:100%宽度表,具有隐藏溢出和不规则/最小细胞宽度的细胞
没有回答,我想知道现在是否可以。
这是jsfiddle上的一个示例:https://jsfiddle.net/gd1fogee/
这是一个片段:
table{
width:100%;
}
td{
/*max-width: 150px !important; */
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
padding: 3px 5px;
}
<div style="width:400px;display:block;">
<table>
<tr>
<td>one</td><td>two</td><td>three</td>
</tr>
<tr>
<td>this is a very very long text to show what i want to achieve</td><td>two</td><td>three</td>
</tr>
</table>
</div>
预先感谢您的帮助!
我不知道这是否是你想要的,但是这里是。
https://jsfiddle.net/tanikimura/4vypvwcn/
将文本跨流应用于p标签。
table{
width:100%;
}
td {
max-width: 150px !important;
}
td p{
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
padding: 3px 5px;
}
<div style="width:400px;display:block;">
<table>
<tr>
<td>one</td><td>two</td><td>three</td>
</tr>
<tr>
<td><p>this is a very very long text to show what i want to achieve</p></td><td>two</td><td>three</td>
</tr>
</table>
</div>
当某些内容太大时,您无法真正使其大小相对于内容...因此您必须通过选择的最大宽度方法进行操作。如果将一堂课放在需要受到限制的列上,那将使内容更大,这可能会使它更加相对尺寸。如果只有两个左右的列,则针对特定的TR的特定儿童TD,这些列将具有超大内容。否则将最大宽度应用于所有宽度。
所以...我正在尝试考虑一个不错的JS解决方案。不过,这是一个需要改善的需求。如果有人看着这个并想改进它,请成为我的客人,并在评论中告诉我。
const table = document.getElementsByTagName('table')[0];
shrinkCells(table, .75);
function shrinkCells(tbl, maxWidth) {
// Check if it fits within the parent
if (tbl.offsetWidth <= tbl.parentElement.offsetWidth || maxWidth < .2) {
return tbl;
}
// set the maxWidth for every element that is bigger than the current maxwidth
Array.from(table.getElementsByTagName('td')).forEach(function (el) {
if (el.offsetWidth > (tbl.offsetWidth * maxWidth))
el.style.maxWidth = (tbl.offsetWidth * maxWidth) + "px";
});
shrinkCells(tbl, maxWidth - .05);
}
table{
width:100%;
border-collapse: collapse;
}
td{
border: solid 1px #000;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
padding: 3px 5px;
}
<div style="width:400px;display:block;">
<table>
<tr>
<td>one</td><td>two</td><td>three</td>
</tr>
<tr>
<td>this is a very very long text to show what i want to achieve asdhudfaslkjdfhdf asdf asdfasdfa asdf asdfasdf asdf a</td><td>two asdf asd fasd fasd fradfsddf asdf asdf asd fdsaf</td><td>three</td>
</tr>
</table>
</div>
再次,这是为了乐趣而写的。让我知道什么可以改变以使其变得更好。
将近5年后,我仍然无法使用表找到完美的解决方案,但是我发现了使用网格及其列及其列自动宽度的解决方法:
grid-template-columns: repeat(3, auto);
.grid{
width:100%;
display:grid;
grid-template-columns: repeat(3, auto);
}
.grid div{
/*max-width: 150px !important; */
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
padding: 3px 5px;
}
<div style="width:400px;display:block;">
<div class="grid">
<div>one</div><div>two</div><div>three</div>
<div>this is a very very long text to show what i want to achieve</div><div>two</div><div>three</div>
</div>
</div>