Home > Web Front-end > CSS Tutorial > How to Properly Truncate Long Text in Table Cells with CSS?

How to Properly Truncate Long Text in Table Cells with CSS?

Linda Hamilton
Release: 2024-12-21 19:34:11
Original
212 people have browsed it

How to Properly Truncate Long Text in Table Cells with CSS?

How to Use CSS text-overflow in a Table Cell

You may encounter a situation where you want to display text in a table cell, but the text is too long to fit comfortably on a single line. You'd like to clip the text with an ellipsis ('...') instead of allowing it to wrap onto multiple lines.

To achieve this, you can leverage CSS properties like 'text-overflow' and 'overflow'. However, using 'white-space: nowrap' can lead to a specific issue: the text and its cell might continuously expand right, extending beyond the intended table width.

To resolve this issue, you need to set the 'max-width' CSS property for each 'td' class. Setting 'max-width' ensures that the overflow behavior works as expected:

td {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
Copy after login

In responsive layouts, you can use 'max-width' to specify the minimum width of the column. Alternatively, you can use 'max-width: 0' for unlimited flexibility. You should also set a width for the containing table (e.g., width: 100%). Set the width of each column as a percentage of the total width:

table {
  width: 100%;
}

td {
  max-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

td.column_a {
  width: 30%;
}

td.column_b {
  width: 70%;
}
Copy after login

Note that a table layout issue specific to IE 9 (or less) may require additional HTML code:

<!--[if IE]>
<style>
  table {
    table-layout: fixed;
    width: 100px;
  }
</style>
<![endif]-->
Copy after login

The above is the detailed content of How to Properly Truncate Long Text in Table Cells with CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template