CSS: Top vs Margin-top

后端 未结 5 537
-上瘾入骨i
-上瘾入骨i 2020-11-29 17:56

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?

5条回答
  •  无人及你
    2020-11-29 18:35

    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:

    content

    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!

提交回复
热议问题