Home > Article > Web Front-end > Why Doesn't 'margin: auto' Center Absolutely or Fixed Positioned Elements?
Centering Positioned Elements: Beyond 'margin: auto'
In CSS, centering an element using the margin: auto property can be tricky when dealing with elements positioned absolutely or fixed. To understand this behavior, we need to delve into the CSS specification.
In-Flow Element Centering
For in-flow elements (without absolute or fixed positioning), setting both margin-left and margin-right to auto achieves horizontal centering relative to the containing block. This works because the CSS specification dictates that if both margins are set to auto, they must be equal, resulting in the element being centered.
Absolute and Fixed Element Centering
However, when it comes to absolutely or fixed elements, the situation is different. The CSS specification states that:
Setting Left and Right to Zero
To center an absolutely or fixed element using margin: auto, you must also set both left and right to 0. This forces the browser to compute margin-left and margin-right equally, resulting in horizontal centering.
However, if you specify any other value for left or right, centering will not occur unless you also set width. Omitting one of these properties will result in a non-centered element.
Real-World Example
Consider the following code:
.box { height: 50px; border: 1px solid; position: relative; } .box > div { position: absolute; left: 0; right: 0; margin: auto; width: 200px; background-color: red; color: #fff; }
In this example, setting left: 0 and right: 0 ensures that the div is always flush with the left and right edges of the box. The margin: auto property then centers the div horizontally within the box.
The above is the detailed content of Why Doesn't 'margin: auto' Center Absolutely or Fixed Positioned Elements?. For more information, please follow other related articles on the PHP Chinese website!