Center bootstrap table with 100% width?

2019-07-16 04:28发布

问题:

https://jsfiddle.net/t4ura97t/

<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>

Is it possible to center this table without giving the table a width other than 100%? Most of the answers I've found for doing this all give the table a width less than 100%. This isn't very nice since when you then center the element if the display is big enough the table still appears to not be centered.

回答1:

Use mx-auto w-auto to horizontal center. Also, the table should be inside table-responsive...

https://www.codeply.com/go/gotnKXfdw2

<div class="table-responsive">
    <table class="table table-striped table-hover mx-auto w-auto">
        <thead>
            <tr>
                <th scope="col">column1</th>
                <th scope="col">column2</th>
                <th scope="col">column3</th>
            </tr>
        </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>


回答2:

You must put your table inside a div with table-responsive class like below,

<div class="table-responsive">
<table class="table table-striped table-hover">
  <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>

Update: To center table with not 100% width do like above, and give below style to your .table class.

{
   width:auto;
   margin:0 auto;
}


回答3:

hope this works:

 <div class="container  table-responsive">   
        <table class="table table-striped table-hover ">
            <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>
            </div>