I had previously thought that both of the code blocks below would correctly center a div (with some issues with older browsers of course). The first method uses text-align: center
whereas the second method uses left and right margins of auto
. However, the first block of code below does not center the inner div as I was expecting. Any ideas why?
<div style="text-align: center; background-color: red;">
<div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue">Not working</div>
</div>
The following code does center the div:
<div style="background-color: red;">
<div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; margin-left: auto; margin-right: auto">Works</div>
</div>
Here is my JSFiddle