简体   繁体   中英

Cannot center inner div with text-align: center

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

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>

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; margin-top: 0; margin-bottom: 0; margin-left: auto; margin-right: auto;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM