gte_ gte_ - 4 months ago 7
HTML Question

Horizontal center table inside div

I am a beginner HTML/CSS student. I started making a website for fun, but I encountered a problem. When I set an entire table inside

<div>
tags, and set the above styling, the table is not being centered.

The HTML and CSS looks somewhat like this:

CSS



div{
border: 5px solid white;
border-radius: 5px;
margin: auto;
text-align: center
}


HTML



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


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

Thanks and have a nice day.

Answer

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