You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在保持Bootstrap表格宽度为100%的情况下居中显示?

当然可以!我之前也纠结过这个问题——不想给表格设固定的窄宽度,又要让它在大屏上看起来真正居中,其实结合Bootstrap自带的工具类就能轻松解决,不需要写太多自定义CSS。

方案1:让表格宽度随内容自适应,同时整体居中

Bootstrap 4自带了.table-auto类,它会取消表格默认的width:100%,让表格宽度根据内容自动调整。再配合Bootstrap的.mx-auto工具类(设置左右margin为auto),就能让自适应宽度的表格在页面水平居中。

代码示例:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

<table class="table table-striped table-hover table-responsive table-auto mx-auto">
<thead>
<th scope="col">column1</th>
<th scope="col">column2</th>
<th scope="col">column3</th>
</thead>
<tbody>
<tr>
<td>item1</td>
<td>item2</td>
<td>item3</td>
</tr>
<tr>
<td>item1</td>
<td>item2</td>
<td>item3</td>
</tr>
</tbody>
</table>

这种方式的好处是:当内容较少时,表格会收缩到内容宽度并居中;当内容足够多时,表格会自动撑满可用空间(不会超出容器范围),视觉上完全贴合居中的布局,不会出现“窄表格居中但内容偏左”的尴尬情况。

方案2:表格始终占满容器宽度,容器在页面居中

如果你的需求是表格保持100%宽度(相对于父容器),同时让父容器在大屏上有合理的最大宽度并居中,直接用Bootstrap的.container类包裹表格即可:

代码示例:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

<div class="container">
  <table class="table table-striped table-hover table-responsive">
  <thead>
  <th scope="col">column1</th>
  <th scope="col">column2</th>
  <th scope="col">column3</th>
  </thead>
  <tbody>
  <tr>
  <td>item1</td>
  <td>item2</td>
  <td>item3</td>
  </tr>
  <tr>
  <td>item1</td>
  <td>item2</td>
  <td>item3</td>
  </tr>
  </tbody>
  </table>
</div>

.container类会根据屏幕尺寸自动设置最大宽度,并且默认水平居中。表格在容器内保持100%宽度,既不会在大屏上显得过于空旷,又不需要给表格设置小于100%的固定宽度。

特殊情况:如果没有.table-auto类

如果你用的Bootstrap版本恰好没有.table-auto(不过你用的4.1.0已经包含这个类了),也可以手动添加一行自定义CSS来实现相同效果:

.table-content-auto {
  width: auto !important;
}

然后给表格加上table-content-auto类,再配合.mx-auto就能达到自适应宽度+居中的效果。

内容的提问来源于stack exchange,提问作者Renari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:31:25