Reputation: 31
MDN suggests that margin-left: auto
with position: absolute
will set the left margin to 0, but that does not seem to be the case in practice. I am now wondering if it is a bug in the browser, or in the MDN documentation as my example seems to align to the right.
fixed or absolute
0, except if both margin-left and margin-right are set to auto.
This example has margin-left
set to auto
and margin-right
unspecified (i.e. initial value of 0) and the left margin appears to be computed as taking the remaining space rather than 0 as suggested by the source above: https://jsfiddle.net/40txneL7
I have also found a snippet in the spec suggesting that the remaining space is divided between the auto
margins, and not set to 0 if just one axis margin is set.
Is MDN documentation incorrect here, or am I missing something?
Upvotes: 2
Views: 364
Reputation: 272807
There are a lot of rules concerning the width and the placement of the position absolute that you can read about here: https://www.w3.org/TR/css-position-3/#abs-non-replaced-width
The constraint that determines the used values for these elements is:
left + margin-left + border-left-width + padding-left + width + padding-right + border-right-width + margin-right + right = width of containing block
We don't have padding and the following rule apply:
If none of the three is auto: ... If one of
margin-left
ormargin-right
is auto, solve the equation for that value. If the values are over-constrained, ignore the value for left
So you will have
0px(left) + margin-left + 200px(width) + 0px(margin-right not specfied) + 0px(right) = width of containing block
The containing block in your case is the viewport so we have 100% of screen width. If we solve the equation you will get
margin-left = viewport width - 200px
so not equal to 0. You can verify this by checking the Dev tool
We set 0 for margin for the other cases. If you continue reading the Spec you can find:
Otherwise, set auto values for
margin-left
andmargin-right
to 0, and pick one of the following six rules that apply.
Upvotes: 3
Reputation: 800
The current position of your absolutely positioned element is not due to margin-left: auto
as you assume but to right: 0
since it overrides the left: 0
property.
Just remove right: 0
and you will see that your element is positioned left ignoring the margin-property.
Upvotes: -1