I have two HTML elements - one is div
another is a table
. both of them have two elements - div has p
and table has td
. Both of them have the same style.
Code:
.container {
display: flex;
flex-direction: row;
}
p, td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<div class="container" style="width:100px; background-color: red">
<p width="50px">
Hello world
</p>
<p width="50px">
Hello world
</p>
</div>
<table style="background-color: green">
<tr width="100px">
<td width="50px">Hello World</td>
<td width="50px">Hello World</td>
</tr>
</table>
And their parent has 100px
width. Actually, I want them to truncate if their size overflowed. For div
, I get my desired output but in table
, I do not get the same result. why does this happen? Is it because table
has a different default style than div
?
CodePudding user response:
It happens because of the display property in table. You need to give a display: block
to make ellipsis work, but it kind of removes how tables should work.
The better thing would be to wrap your td
contents inside a div
and change your CSS.
Option 2 would be using max-width to your
td`.
<td width="50px">
<div>Hello World</div>
</td>
CSS to:
td>div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 50px
}
OR Just add max-width
.container {
display: flex;
flex-direction: row;
}
p,
td>div,td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 50px;
}
<div class="container" style="width:100px; background-color: red">
<p width="50px">
Hello world
</p>
<p width="50px">
Hello world
</p>
</div>
<table style="background-color: green">
<tr width="100px">
<td width="50px">
<div>
Hello World</div>
</td>
<td width="50px">
<div>
Hello World</div>
</td>
<td width="50px">
Hello World
</td>
</tr>
</table>
CodePudding user response:
Instead of giving width to tr and td, give width to the table.
table {
background-color: green;
table-layout: fixed;
width: 100px;
}
td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<table>
<tbody>
<tr>
<td>Hello World</td>
<td>Hello World</td>
</tr>
</tbody>
</table>
CodePudding user response:
To clip text with an ellipsis when it overflows a table cell, you will need to set the max-width CSS property on each td class for the overflow to work.
.container {
display: flex;
flex-direction: row;
}
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
td
{
max-width: 50px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
<div class="container" style="width:100px; background-color: red">
<p width="50px">
Hello world
</p>
<p width="50px" >
Hello world
</p>
</div>
<table style="background-color: green">
<tr>
<td>Hello World</td>
<td>Hello World</td>
</tr>
</table>