In this post, we will explain when and why margin auto does not work in CSS.
What is margin Property?
CSS “margin” property is used to create vacant space around the element, which could be from left, right, top, and bottom. The defined space always takes place outside of the selected HTML element.
The value “length” refers to the margin of elements, which can be specified into rem, pt, px, and in other units. Value “auto” allows the browser to adjust the margin.
To overview the margin property deeply, you can check out this dedicated article.
When and Why margin auto Does not Work in CSS?
Each HTML element has a display type by default, one is “block”, and the other is “inline”. In HTML, some are block level elements, and some are inline elements by default. Block level elements have predefined 100% width, while inline elements have no predefined width or padding.
Block Type HTML Element
Here in our HTML file, two “<p>” tags that have been defined with some text within the body section:
The display value as block will be applied by default to <p> element and it will consume the 100% width as shown below:
Now, let’s add the “margin” property with “auto” value to our block type element <p> along the “width” of “50px”:
After saving the mentioned code, notice that the predefined width has been overridden with 50px and margin auto has adjusted the element into the center:
Let’s move ahead toward inline type HTML elements.
Inline Type HTML Element
As the below image shows that when we have declared some text within <span> tags, they did not consume any space; it is only because the inline display value has been applied by default on this element:
Now, if we will apply the width property or margin property with auto value on the span element. As a result, no effects will take place. Because when the display inline is applied, it makes the element bound to consume only the space that exists within its tags.
If the display property for an element is set to inline by default, you can override it by specifying the value block of the display property by yourself.
Have a look below at the explained example.
Let’s intentionally use an element with predefined inline value, such as <span>:
In the next step, utilize the display property along the value “block”. Set the width to 50px and margin to auto as explained:
We have elaborated on when and why margin auto does not work in CSS.
The margin auto does not work with elements that have inline display by default, such as span. Only the elements with predefined display block work with auto margin. However, you can override the inline behavior of an element and make it behave like a block type element. This article discussed why and when margin auto does not work within CSS.