我如何在Bootstrap中将表格水平居中

Amo*_*wad 9 html twitter-bootstrap

这是我的代码。我正在尝试做的就是将此表放在容器的中央。但是,当我使用“容器”类时,默认情况下它会向左对齐,当我将div使用“容器-流体类”时,它将使用全宽。我想将桌子水平居中。有人可以帮忙吗?

<!-- Container (Pricing Section) -->
<div id="pricing" class="container-fluid">
<table class="table table-bordered table-striped">
<thead><tr>
<th>Material Name</th>
<th>Rate (INR)</th>
</tr>
</thead>
<tbody style="">
<tr>
<td>Books</td>
<td>7.00(per KG)</td>

</tr>
<tr>
<td>Soft Plastic</td>
<td>15.00(per KG)</td>

</tr>
<tr>
<td>Hard Plastic</td>
<td>2.00(per KG)</td>

</tr>
</tbody>
</table>
<div>
Run Code Online (Sandbox Code Playgroud)

这是一个屏幕 截图

我知道“容器流体”使用全宽度,但我也只使用了“容器”类,但这无济于事。请指教...

GKi*_*lin 11

<div class="table-responsive">
    <table class="mx-auto w-auto">
      ....
    </table>
</div>
Run Code Online (Sandbox Code Playgroud)

中心引导表中获取解决方案,宽度为 100%
来自@Rene Hamburger 的评论:如链接的答案所示,w-auto表格需要保持其原始的自然宽度。否则它会被调整为 100%。


CeA*_*ado 10

要使表格本身水平居中,可以在CSS中使用marginwidth属性。

.table {
   margin: auto;
   width: 50% !important; 
}
Run Code Online (Sandbox Code Playgroud)

现在,对于表的内容,您可以同时使用CSS和Bootstrap印刷类。在这种情况下,将CSS用于th元素以及.text-center表中的类。

table th {
   text-align: center; 
}

<table class="table table-bordered table-striped text-center">
    <!-- Content of the table -->
</table>
Run Code Online (Sandbox Code Playgroud)

在这里,您可以在.container-fluid.container类中看到它:

.table {
   margin: auto;
   width: 50% !important; 
}
Run Code Online (Sandbox Code Playgroud)
table th {
   text-align: center; 
}

<table class="table table-bordered table-striped text-center">
    <!-- Content of the table -->
</table>
Run Code Online (Sandbox Code Playgroud)

  • 进入 CSS 并添加一些代码是一个穷人的解决方案。bootstrap等样式表之所以如此完善,正是为了避免黑掉css。 (3认同)

Lui*_*ves 6

text-center只需在表类中添加一个类:

<table class="table text-center"> 
... 
</table>
Run Code Online (Sandbox Code Playgroud)

它是 Bootstrap 中的一个本地类,允许水平对齐。


Kat*_*Kat 6

无论表或屏幕的大小如何,使用此Bootstrap行/列组合都可以使用,无需CSS:

<div class="row justify-content-center">
    <div class="col-auto">
      <table class="table table-responsive">
        ....table stuff....
      </table>
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

  • 这是用于引导程序 4。 (3认同)

Hea*_*ner -1

带有CSS

.table td {
   text-align: center;   
}
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/8s9918my/

或者引导程序:

<table class="table text-center">
Run Code Online (Sandbox Code Playgroud)

  • 这似乎对我不起作用。桌子仍然在左边。 (2认同)