Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to horizontally center table inside div?

Tags:

html

css

I have a <table> inside a <div>, with the styling below, the table is not being centered, why?

Shouldn't everything within the <div> be formatted like I styled in the CSS?

HTML

<div> 
  <table></table> 
</div> 

CSS

div{ 
  border: 5px solid white; 
  border-radius: 5px; 
  margin: auto; 
  text-align: center;
} 
like image 388
gte_ Avatar asked Jul 10 '16 15:07

gte_


3 Answers

You are setting margin: auto on the div, so the div will be centred … however you have also left the div as width: auto so it will be as wide its container (once you account for margins, padding and borders).

You are setting text-align: center on the div, so the inline children of the div will be centred, but the table is not inline, so it isn't affected (some of the table cells contents might be, depending on inheritance).

If you want to centre the table then you have to centre the table itself.

table { margin: auto; }
like image 86
Quentin Avatar answered Oct 26 '22 23:10

Quentin


The div element is block-level, and a block-level element occupies the entire space of its parent container, so margin: auto; does not take any effects by default. And text-align: center; works only for the inline-level children, but table is not one of them.

You can set the table as inline table display: inline-table;, so all the inline children including the table will be centered by text-align: center; on the parent div.

div {
  border: 1px solid red;
  text-align: center;
}
table {
  border: 1px solid blue;
  display: inline-table;
}
<div>
  <table>
    <tr>
      <td>Hello world</td>
    </tr>
  </table>
</div>
like image 23
Stickers Avatar answered Oct 27 '22 01:10

Stickers


You might want to use

table{
    margin: auto;
}

Here is a fiddle : https://jsfiddle.net/7mhpv51s/1/

like image 41
Cephou Avatar answered Oct 27 '22 01:10

Cephou