Truncating Text in Table Cells with CSS Text-Overflow
In web design, the need to handle text that exceeds the width of table cells arises frequently. Using CSS, you can truncate text with an ellipsis to prevent wrapping while maintaining a concise and organized table layout.
Problem: Despite attempts to apply CSS overflow and text-overflow attributes, text within table cells continues to wrap to multiple lines or expands beyond the table width.
Solution: To effectively truncate text with an ellipsis, you must also set the max-width property for each table cell (td) class. This constraint allows text to be clipped at the specified width.
Here's the updated CSS code:
td { max-width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
To ensure responsiveness, consider using max-width: 0px; for unlimited width flexibility. You can also set a specific width for the containing table (typically width: 100%;) and define the column widths as percentages of the total width.
For example:
table { width: 100%; } td { max-width: 0px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } td.column_a { width: 30%; } td.column_b { width: 70%; }
Note: For Internet Explorer 9 or below, you may need to add the following HTML to fix a rendering issue:
<!--[if IE]> <style> table { table-layout: fixed; width: 100px; } </style> <![endif]-->
By following these steps, you can effectively truncate text in table cells with an ellipsis, ensuring a clean and controlled table layout.
The above is the detailed content of How to Properly Truncate Text in Table Cells with CSS?. For more information, please follow other related articles on the PHP Chinese website!