1.position:absolute;left:200px;
2.position:absolute;margin-left:200px;
Is there any differences about the above style?
1.position:absolute;left:200px;
2.position:absolute;margin-left:200px;
Is there any differences about the above style?
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.
Even though they can do similar things, they are completely different.
Margin is part of the box model, which also includes padding
and border
. Box model styles change the size of the object itself.
For instance, if you have an image with the below style:
.my_box {
display:block;
margin-left:10px;
}
The elements with the my_box
class would get 10 pixels margin added on the left side of the box.
Top, left, etc
These are positions
, which instead of adding to the size of the elements box model, literally tell the elements where to be.
.my_box {
display:block;
left:10px;
}
The above style would tell that element to be 10 pixels from the left of its container (if position:relative
, or the page (if position:absolute
).
Yes, there is difference.
See fiddle: http://jsfiddle.net/xk8Lz/
Attention to 10px padding
in "parent" elements to absolute positioned element. Paddings and borders will affect margin in absolute positioned Div.
Left will count from beginning of "parent" element.
Code:
<div class="left">
left parent
<div class="abs">Left</div>
</div>
<div class="marginLeft">
margin left parent
<div class="abs">Margin-Left</div>
</div>
Css:
div, span {
border: 1px solid #000;
height: 80px;
width: 80px;
}
.left, .marginLeft {
background: #aaf;
margin: 10px 0 0 10px;
padding: 10px;
position: relative;
}
.marginLeft {
}
.abs {
background: #faa;
position: absolute;
top: 0;
}
.left .abs {
left: 100px;
}
.marginLeft .abs {
margin-left: 100px;
}