1

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

kojow7
  • 10,308
  • 17
  • 80
  • 135
  • 1
    Possible duplicate of [Horizontally center a div in a div](http://stackoverflow.com/questions/114543/horizontally-center-a-div-in-a-div) – GillesC Oct 27 '15 at 23:16
  • No, it is not a duplicate. I already knew how to center a div as specified in the second example I posted. I was wondering why the first example did not work. Pete gave the answer below. – kojow7 Oct 28 '15 at 01:02

2 Answers2

3

It's a block-level element, its position won't be effected by the text-align property. If you set it to display-inline, it will work.

<div style="text-align: center; background-color: red;">
    <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; display: inline-block;">It will work now</div>
</div>
Pete
  • 532
  • 5
  • 11
0

The div that is centered has margin-left: auto and margin-right: auto, the div that doesn't work lacks any margins.

See this DEMO

On the top box, I added: margin: 0 auto which is shorthand for: margin-top: 0; margin-bottom: 0; margin-left: auto; margin-right: auto;

zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • Yes, I typed the code myself so already knew that the first example did not have margins set to auto. I was wondering why text-align did not work as was answered by Pete above. – kojow7 Oct 28 '15 at 01:05