如何使用 CSS 防止表格單元格中的文字換行?


要使用 CSS 防止表格單元格中的文字換行,這有助於提高可讀性。在本文中,我們將瞭解如何使用 CSS 的 white-space 屬性來防止表格單元格中的文字換行。

我們有一個 5*3 的表格,其中包含一些資料,我們的任務是使用 CSS 防止表格單元格中的文字換行。

防止表格單元格中的文字換行的步驟

我們將按照下面提到的步驟來防止表格單元格中的文字換行

  • 我們使用 table 標籤建立了一個表格,使用 theadtbody 指定表格的表頭和主體部分。我們使用 tr 標籤建立行,使用 th 標籤建立表頭,使用 td 標籤輸入單元格值。
  • 然後,我們使用 CSS 屬性設計表格,例如 border-collapse 來摺疊邊框,使用 text-align 居中對齊文字,使用 border 屬性新增邊框,並新增表格標題的 background-color
  • 我們在表頭中使用了 "white-space: nowrap;",它可以防止表格單元格中的文字換行。

示例

這是一個完整的示例程式碼,實現了上述步驟,使用 white-space: nowrap 屬性防止表格單元格中的文字換行。使用者可以嘗試更改瀏覽器視窗的寬度,並觀察表格標題不會換行。

<html>
<head>
    <style>
        table {
            border-collapse: collapse;
            width: 50%;
        }
        th,td {
            padding: 8px;
            text-align: center;
            border: 1px solid black;
        }
        th {
            background-color: #04af2f;
            color: white;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <h2>
        Preventing Text in a Table Cell from Wrapping 
        Using CSS
    </h2>
    <p>
        In this example we have used <strong>white-space: 
        nowrap;</strong> property to prevent text in a 
        table cell from wrapping using CSS.
    </p>
    <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>

結論

在本文中,我們學習並瞭解瞭如何防止表格單元格中的文字換行。我們可以透過防止文字換行來避免可讀性問題。我們在本文中使用了 white-space 屬性。

更新於: 2024年8月13日

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.