CSS: Top vs Margin-top
Solution 1:
You'd use margin, if you wanted to move a (block) element away from other elements in the document flow. That means it'd push the following elements away / further down. Be aware that vertical margins of adjacent block elements collapse.
If you wanted the element to have no effect on the surrounding elements, you'd use positioning (abs., rel.) and the top
, bottom
, left
and right
settings.
With relative
positioning, the element will still occupy its original space as when positioned statically. That's why nothing happens, if you just switch from static
to relative
position. From there, you may then shove it across the surrounding elements.
With absolute
positioning, you completely remove the element from the (static) document flow, so it will free up the space it occupied. You may then position it freely - but relative to the next best non-statically positioned element wrapped around it. If there is none, it'll be anchored to the whole page.
Solution 2:
top
is for tweak an element with use of position
property.margin-top
is for measuring the external distance to the element, in relation to the previous one.
Also, top
behavior can differ depending on the type of position, absolute
, relative
or fixed
.
Solution 3:
Margin applies and extends / contracts the element's normal boundary but when you call top you are ignoring the element's regular position and floating it to a specific position.
Example:
html:
<div id="some_element">content</div>
css:
#some_element {margin-top: 50%}
Means the element will begin displaying html at the 50% height of its container (i.e. the div displaying the word "content" would be displayed at 50% height of its containing div or html node directly before div#some_element) but if you open your browser's inspector (f12 on Windows or cmd+alt+i on mac) and mouse over the element you will see it's boundaries highlighted and notice the element has been pushed down rather than re-positioned.
Top on the other hand:
#some_element {top: 50%}
Will actually reposition the element meaning it will still display at 50% of its container but it will reposition the element so its edge starts at 50% of its containing element. In other words, there will be a gap between the edges of the element and its container.
Cheers!
Solution 4:
The top
property is a position property. It is used with the position
property, such as absolute
or relative
. margin-top
is an element's own property.