Why won’t margin: auto; work?

By June 12, 2015Uncategorized

If you’ve ever done theme customization or a fair amount of CSS work, you’ve run into this issue before.

You want to center a horizontal menu or an image or something and you can’t seem to get margin: auto; to do what it’s supposed to.

I just ran into this with a theme I updated.  After the update the entire header was slammed flush to the left of the browser while the rest of the site underneath is was centered in a boxed style. I really needed the menu back in the center with the rest of the site so I dug into the CSS in chrome by pressing F12.

Looked at each element and drilled down until I have the header highlighted.

It’s container was full width and the header itself had a width of 1000 pixels.  It should be simple. I knew from experience that all I needed to do was add

margin: auto;

to the CSS of the element and it would center itself.  It needed to have a width specified for it to work -and it had one.  Easy.

But it didn’t work.

Ok, so… maybe there was something in the theme that was overriding my CSS?  I edit the CSS to try and compensate with

margin: 0 auto !important;

Still didn’t work.  It was being stubborn. It wouldn’t center no matter how important I tried to make it.

This launched me on a hunt for why.  And I found the answer.  I’ll share it with you here to save you the look.

In order for margin: auto; to work, you need to check and make sure all the following are true for the element:

.centerit {
width: 1000px;
display: block;
position: relative;
float: none;
margin: 0 auto;


The element you are trying to give an auto margin needs to have a width defined.
Sometimes this is all you need to set on an element for an auto margin to work. If it doesn’t work, your element is inheriting a property from a parent that’s inhibiting it from working.
The following properties will need to be set for the element to override any inherited ones.


There are many display types for elements. An auto margin will not work in all of them such as “inline”.
Setting the element to display as a block element is safe and will work.


The element needs to be relatively positioned.


The element can’t have a float applied. Assigning it float: none; handles this.

Hope this helps at least one person out there. 🙂

Leave a Reply