Home >Web Front-end >CSS Tutorial >How to Prevent Table Cell Expansion Due to Long Text?

How to Prevent Table Cell Expansion Due to Long Text?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 05:12:15728browse

How to Prevent Table Cell Expansion Due to Long Text?

How to Prevent Table Cell Expansion Despite Text Length

In a typical table layout, the width of a column adjusts to accommodate the length of its longest cell. However, if you desire a fixed column width regardless of the text within its cells, follow these steps:

Solution:

  1. Define the cell width using CSS: Specify the width (e.g., 100px) for both th and td elements within the table definition.
  2. Set table-layout to fixed: This property ensures that the table width stays constant, discouraging column expansion. To fully control the table's dimensions, set a width for the table itself (e.g., width: 200px).
  3. Enable text clipping (optional): To prevent text from overflowing outside the cell, add overflow: hidden to the cell definitions.

Example:

table {
  table-layout: fixed;
  width: 200px;
}

th,
td {
  width: 100px;
  overflow: hidden;
}
<table>
  <tr>
    <th>header 1</th>
    <th>header 234567895678657</th>
  </tr>
  <tr>
    <td>data asdfasdfasdfasdfasdf</td>
    <td>data 2</td>
  </tr>
</table>

By adhering to these steps, you can ensure that table column widths remain fixed, regardless of the text length in its cells. This approach grants you greater control over table presentation and prevents unwanted column expansion that may disrupt your layout.

The above is the detailed content of How to Prevent Table Cell Expansion Due to Long Text?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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