1

I am trying to center a table within a div but the table can be of varying length. The code looks something like this:

<div>
     <table>
     <tr> .... </tr>
     </table>
</div>

The div element is of course display:block and of course takes up the entire horizontal space on the page but I cannot figure out how to set the padding to auto and just center the table in the div

Can anybody help me with this?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Walker Farrow
  • 3,579
  • 7
  • 29
  • 51

2 Answers2

2

If the table has an explicit width, you could just use margin: 0 auto to center it.

table { margin: 0 auto; }

Alternatively, if you want to use flexboxes, set the display of the parent element to flex, and use justify-content: center for horizontal centering.

.parent {
    display: flex;
    justify-content: center;
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Thanks! This worked perfect. Now, the only problem is that the "max-width:600px; style attribute that I put on the div element gets overidden and it gets expanded to the entire page. Any way to solve this? – Walker Farrow Jan 30 '15 at 00:00
  • @WalkerFarrow I'd suggest reading up on [CSS specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity). If you make an [example](http://jsfiddle.net), I can look at it. – Josh Crozier Jan 30 '15 at 00:02
2

Tables are block level elements. You can set the width of the table and set margin: auto

If the width varies you may be able to use a percentage or a combination of width and min/max-width.

philipb3
  • 279
  • 1
  • 11
  • Thanks! I realized the flex example below was useful, but the main thing that I was being oblivious of was that tables are block-level elements! Duh... Thanks - my problem is now fixed. – Walker Farrow Jan 30 '15 at 00:10