Clip long text inside HTML table cells, show entire content on hover
Using Tootips gives a solution,
<html>
<table border="1" >
<tr>
<td>A</td>
<td><abbr title="Ab df df dfdf df dfdkjf sdfk dfdf">Ab df df</abbr> </td>
</tr>
<tr>
<td>B</td>
<td><abbr title="Bb df df dfdf df dfdkjf sdfk dfdf">Bb df df</abbr> </td>
</tr>
</table>
</html>
Solution:
- Use
table-layout: fixed
so that your table columns maintain fixed size - Wrap the content inside div elements and manipulate width and overflow properties
/*
* fixed table layout
*/
table {
table-layout: fixed;
width: 400px;
font: larger monospace;
border-collapse: collapse;
}
th:nth-child(1) {
width: 20%;
}
th:nth-child(3) {
width: 20%;
}
/*
* inline-block elements expand as much as content, even more than 100% of parent
* relative position makes z-index work
* explicit width and nowrap makes overflow work
*/
div {
display: inline-block;
position: relative;
width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
vertical-align: top;
}
/*
* higher z-index brings element to front
* auto width cancels the overflow
*/
div:hover {
z-index: 1;
width: auto;
background-color: #FFFFCC;
}
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td><div>John Smith</div></td>
<td><div>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div></td>
<td><div>1-234-567890</div></td>
</tr>
<tr>
<td><div>Jane Doe</div></td>
<td><div>Suspendisse lacinia, nunc sed luctus egestas, dolor enim vehicula augue.</div></td>
<td><div>1-234-567890</div></td>
</tr>
</tbody>
</table>
.cell {
max-width: 50px; /* tweak me please */
white-space : nowrap;
overflow : hidden;
}
.expand-small-on-hover:hover {
max-width : 200px;
text-overflow: ellipsis;
}
.expand-maximum-on-hover:hover {
max-width : initial;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th>
ID
</th>
<th>
Adress
</th>
<th>
Comment
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1
</td>
<td class="cell expand-maximum-on-hover">
A very, very long adress that cannot be showed entirely
</td>
<td class="cell expand-small-on-hover">
A very, very long comment to add more information to the row it belongs to.
</td>
</tr>
</tbody>
</table>
You might begin from there, this is an example of how to use max-width
combined with overflow : hidden
.
Pass hover the adress cell to see the result