When and why margin auto does not work in CSS?

margin: auto; or margin: 0 auto; is a very popular technique in CSS that is most commonly used to center an element by the developers.

However, if you apply it to an element without proper understanding, it might not work for you.

The most common reason that the margin: auto; is not working might be that you have not set the width of the element.

If you haven’t set the width of the element and try applying margin: auto;, it will not work. This is because by default the block-level elements such as a div, p, list, etc take up the full width of its parent element, and no space is left to adjust the element horizontally.

So, the very first thing you need to check is whether you have set the width of the element or not. If not please do so.

Here is a working example with and without specifying the width and then applying the margin: auto;

Example:

.div1{
   width: 50%;
   margin: auto;
   background: yellow;
}
.div2{
   margin: auto;
   background: lightblue;
   /* Without width */
}

Reason 2:

Another reason could be that the margin: auto; you are applying to the element is an inline or inline-block level element such as a span, button, img, link, etc.

The margin: auto; does not affect inline and inline-block level elements.

But, if you anyhow want to center the inline elements with margin: auto;, you have to explicitly set the display property to block to make the element a block-level element.

Also, don’t forget to set the width of the element.

Here is a working example with and without applying display: block; and then applying margin: auto; on the element:

Example:

.span1{
   margin: auto;
   background: yellow;
   /* A normal span */
}
.span2{
   display: block;
   width: 30%;
   margin: auto;
   background: lightblue;
   /* span with display: block; */
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.