Skip to content Skip to sidebar Skip to footer

CSS "margin: 0 Auto" Not Centering

Okay I understand that this topic has been covered. But I have looked at various solutions and have had little success with them. I just have no clue why this margin: 0 auto; is n

Solution 1:

It is working.

The problem is you're centering a div, which is a block-level element by default, and which therefore occupies 100% width of its parent (body, in this case). So there's no space to move horizontally, hence no space to center.

For an illustration see this revised demo, which has an added border around .container.

If you reduce the width of .container you'll see the centering work. Here's a second revised demo with width: 50% applied to .container.


Solution 2:

It actually works, but without specifying the width it takes full 100%. Try something like:

   .container {
    margin: 0 auto;
    width:50%;
    }

Hope this may help


Solution 3:

You should specify the width of the div for margin:auto to work. try to use width in percentage to make your div responsive as well.


Solution 4:

You should set a width on .container to let the margin: 0 auto; work. See the updated JSfiddle.


Solution 5:

Another fix that worked for me was to change the display for the parent to display: inline in the CSS and set a max-width so that margin auto centers the text. So far, that has fixed the problem. Not sure if it's the best solution, but it's currently working. See the code below:

.parent-container{
    display: inline;
    max-width: 500px;
    padding: 20px; 
    margin: 0 auto; 
}

Post a Comment for "CSS "margin: 0 Auto" Not Centering"