Difference between "margin-left", and "left" (or "margin-right", and "right")
What is the difference between
margin-left: 10px;
and position: relative; left: 10px;
?
It seems to produce the same result
The simplest way I can explain it is that margin-left
moves the element itself, whereas left
(with position: relative
) pushes other elements away. Although that's not, perhaps the clearest description.
With pictures, though:
+---------------------------------------------------------------------------+--------------+
| |
| +------------------------------------------------------------+ |
| | | |
| | +------------------------------+ | |
| | | | | |
position | | | | | |
<--Left---->|<---margin--->|<---padding-->|<------------width----------->|<---padding-->|<---margin--->|
| | | | | |
| | +------------------------------+ | |
| | | |
| +------------------------------------------------------------+ |
+------------------------------------------------------------------------------------------+
With position: absolute
left also serves to define the distance between the element itself and the left boundary of whatever object the element is positioned against.
When you move something with position:relative
you're not actually moving the space it takes up on the page, just where it is displayed.
An easy way to test this is to use a simple structure like this:
<div id = "testbox">
<img src = "http://www.dummyimage.com/300x200" id = "first">
<img src = "http://www.dummyimage.com/300x200" id = "second">
</div>
with the following CSS:
img{ display:block; }
#first{ margin-top:50px; }
versus this CSS:
img{display:block;}
#first{position:relative; top:50px;}
You'll see that the first moves everything down 50px while the second only moves the first image down (which means it will overlap the second image).
Edit: you can check it out in action here: http://www.jsfiddle.net/PKqMT/5/
Comment out the position:relative;
and top:100px;
lines and uncomment the margin-top
line and you'll see the difference.