首页 > 文章列表 > Bootstrap 4 表格中如何实现列向右对齐?

Bootstrap 4 表格中如何实现列向右对齐?

155 2025-03-15

Bootstrap 4 表格中如何实现列向右对齐?

表格对齐问题

在bootstrap 4中构建表格时,有时会遇到列不对齐的问题。本文将介绍一个解决此问题的方法,以实现列向右对齐。

问题:

假设我们有一个带有四列的表格,前两列使用 th 标签作为标题,后两列使用 td 标签表示数据。然而,我们希望后两列数据向右对齐。

解决方法:

要解决此问题,我们可以采用以下步骤:

  1. 将表格设置成 100% 宽度。
  2. 将第 1、3、4 列设置成固定宽度。
  3. 将第 2 列留空(不设置宽度),使其自动调整宽度以填充剩余空间。

修改后的 html 代码如下:

<table class="table" width="100%">
    <thead>
        <tr>
            <th scope="col" width="20%">#</th>
            <th scope="col" width="20%">First</th>
            <th scope="col" width="20%">Last</th>
            <th scope="col">Handle</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th scope="row" width="20%">1</th>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
        </tr>
        <tr>
            <th scope="row" width="20%">2</th>
            <td>Jacob</td>
            <td>Thornton</td>
            <td>@fat</td>
        </tr>
        <tr>
            <th scope="row" width="20%">3</th>
            <td>Larry</td>
            <td>the Bird</td>
            <td>@twitter</td>
        </tr>
    </tbody>
</table>

通过设置固定宽度和让第 2 列自动调整,我们确保后两列数据始终向右对齐,无论表格的整体宽度如何变化。

来源:1729984312