CSS, why can't you be in the middle?

position: absolute;display: block;width: 80%;margin:0 auto;

Why can I just change it to this? Why not the first one?

position: absolute;display: block;width: 80%;margin:auto;right:0;left:0;
Mar.18,2021

absolute positioning element setting margin 0auto is invalid, you give the width, Then direct left 10%


portal


absolute positioning elements need to be centered. And after using absolute , there will be a BFC feature, and display will automatically become block , and your second sentence will be superfluous.


the first one doesn't work because you set

position: absolute;

but top,bottom,left,right is not specified, the left, top value is the same as the location of the original document stream. That is, it is in the same position as when it static, but does not occupy a place. At this time

margin: 0 auto;

this line of code doesn't really work.

the second can, because you specify left and right as 0, fill the element with the container, and specify the width yourself. The total width is calculated by

.
left + margin-left + border-left-width + padding-left + width + padding-right + border-right-width + margin-right + right = 

margin-left and the value of margin-right to auto is set to 0, so the total width (fixed) = width (fixed) + margin-left + margin-right; (width is 80%). At this point, you can set

position: absolute;
left: 0;
right: 0;
The

code ignores that its function can actually be understood to determine the total width of its elements,

margin: 0 auto;

when margin is set to auto, the left and right margins are evenly divided, the elements are naturally centered, and the principle of vertical centering is the same.


the problem should be position: absolute; absolute positioning, margin:0 auto will not work

Menu