Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between margin-left and left when the position set absolute

1.position:absolute;left:200px;

2.position:absolute;margin-left:200px;

Is there any differences about the above style?

like image 788
damon Avatar asked Sep 12 '13 16:09

damon


1 Answers

There is a subtle difference.

Consider the following example:

<div class="wrap">
    <div class="ex1">Ex 1</div>
    <div class="ex2">Ex 2</div>
    <div class="ex3">Ex 3</div>
</div>

body {
    margin: 0;
}
.wrap {
    margin: 0 50px;
    background-color: lightgray;
    height: 200px;
    width: 400px;
}
.ex1 {
    position: absolute;
    background-color: beige;
    margin-left: 50px;
}
.ex2 {
    position: absolute;
    left: 50px;
    background-color: beige;
    margin-left: 0px;
}
.ex3 {
    position: absolute;
    top: 50px; /* so you can see what is happening */
    left: 0px;
    background-color: beige;
    margin-left: 50px;
}

And see the results at: http://jsfiddle.net/audetwebdesign/WQA6B/

In Example 1 (.ex1), the margin is 50px from the left edge of the parent container (.wrap).

In Example 2 (.ex2) the element is 50px from the left edge of the view port.

To get .ex2 to behave similarly to .ex1, you would need to set position: relative to .wrap so both div's are positioned with respect to the same context.

There is yet another factor. In Example 1, I did not specify any offsets, so the element remains in the position if would have been if you had used position: static, which is why the margin is computed with respect to the left edge of the wrapper.

If I had set left: 0 (see Example 3) you would have gotten a result similar to Example 2.

like image 157
Marc Audet Avatar answered Oct 11 '22 08:10

Marc Audet