如何使用 CSS 防止表格单元格中的文本换行?

cssweb developmentfront end technology更新于 2024/10/17 7:40:17

在 HTML 中,表格有助于在网页上以格式化的方式显示数据。例如,我们可以显示学生、产品、订单、订阅等数据。

有时,我们需要以表格格式显示较长的数据。例如,产品描述可能比其他产品信息更长。因此,在这种情况下,我们必须避免将文本换行到下一行,以保持表格布局的一致性。

我们有一个简单的解决方案来避免表格单元格中的文本换行,即使用 CSS 的"white-space"属性。

语法

用户可以按照以下语法使用 CSS 的 white-space 属性来防止表格单元格中的文本换行。

white-space: nowrap;

在上面的语法中,我们使用了"nowrap"作为"white-space"属性的值,以避免换行。

示例 1

在下面的示例中,我们创建了包含城市数据的表格。此外,我们还在表格标题中添加了长文本。在 CSS 中,我们使用各种属性设置了表格样式。此外,我们还在表格标题中使用了"white-space: nowrap"CSS 属性来避免换行。

在输出中,用户可以尝试更改浏览器窗口的宽度,并观察表格标题是否没有换行。

<html>
<head>
   <style>
      table {border-collapse: collapse; width: 100%; font-size: 1.5rem;}
      th, td {padding: 8px; text-align: left; border: 1px solid blue;}
      tr:hover {background-color: #f5f5f5;}
      th {background-color: #4CAF50; color: white; white-space: nowrap;}
   </style>
</head>
<body>
   <h2> Preventing the text wrap <i> in table cell from wrapping </i> using CSS</h2>
   <table>
      <thead>
         <tr> <th> city - first column </th>  <th> State - second column </th> <th> Population - Third column </th></tr>
      </thead>
      <tbody>
         <tr> <td> Bengaluru </td> <td> Karnataka </td><td> 8.42 million </td>  </tr>
         <tr><td> Mumbai </td> <td> Maharashtra </td> <td> 18.41 million </td> </tr>
         <tr> <td> Delhi </td> <td> Delhi </td> <td> 16.78 million </td> </tr>
         <tr> <td> Hyderabad </td>  <td> Telangana </td> <td> 6.81 million</td> </tr>
      </tbody>
   </table>
</body>
</html>

示例 2

我们在每个表格单元格中添加了下面示例中的长文本内容。此外,我们还为备用表格单元格添加了 CSS 属性"white-space: nowrap"。这意味着在第一列、第三列、第五列等中添加了空白属性。

在输出中,用户可以观察到第二列的文本换行了,但第一列和第三列的文本没有换行。

<html>
<head>
   <style>
      table {border-collapse: collapse; width: 100%;font-size: 1.5rem;}
      th,td {padding: 0.25rem; text-align: left; border: 2px solid blue;}
      /* adding white-space for alternative table columns */
      th:nth-child(2n+1),
      td:nth-child(2n+1) {white-space: nowrap;}
   </style>
</head>
<body>
   <h2> Preventing the text wrap <i> in table cell from wrapping </i> using CSS </h2>
   <table>
      <thead>
         <tr><th> first header </th>
            <th> second header </th>
            <th> Third header </th> </tr>
      </thead>
      <tbody>
         <tr><td> first row, first cell </td>
            <td> first row, second cell </td>
            <td> first row, third cell </td></tr>
         <tr><td> second row, first cell </td>
            <td> second row, second cell </td>
            <td> second row, third cell </td> </tr>
      </tbody>
   </table>
</body>
</html>

用户学会了如何防止表格单元格文本换行。我们可以通过换行来避免可读性问题。在本教程中,我们使用了"white-space"属性,但用户可以尝试使用"overflow"属性。


相关文章


有用资源