Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Top vs Margin-top

I'm not sure if I fully understand the difference between these two.

Can someone explain why I would use one over the other and how they differ?

like image 821
Jason Avatar asked Oct 27 '10 17:10

Jason


People also ask

What is the difference between top and margin-top in CSS?

"Margin is that space between the edge of an element's box and the edge of the complete box, such as the margin of a letter. 'top' displaces the element's margin edge from the containing blocks box, such as that same piece of paper inside a cardboard box, but it is not up against the edge of the container."

Is it better to use margin-top or bottom?

Solution: Always Use Top Margin! The reason is related to the 'C' in CSS. In this article, I'll show you why top margin is better and I'll reveal a deeper CSS principle behind the solution. I'm sure you'll find it valuable.

What does margin-top mean in CSS?

The margin-top CSS property sets the margin area on the top of an element. A positive value places it farther from its neighbors, while a negative value places it closer.

Is margin better than padding?

The margin clears an area around an element (outside the border), but the padding clears an area around the content (inside the border) of an element. it means that your element does not know about its outside margins, so if you are developing dynamic web controls, I recommend that to use padding vs margin if you can.


1 Answers

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.

like image 182
DanMan Avatar answered Sep 29 '22 16:09

DanMan