Why margin-top of the top div would apply to `<body>`?

后端 未结 7 1595
长情又很酷
长情又很酷 2020-12-15 21:26

Here I posted a demo http://jsfiddle.net/LxYMv/1/.

As you can see gets margin-top:10px from the top div, and therefor

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 21:28

    As @Guffa said:

    This is called margin collapsing.

    When an element with a margin is inside an element with no padding or border, the margin will be applied outside the parent element instead of between the child element and the parent edge.

    To elaborate a bit: the solution is to use padding instead of margin. In your case, you'd add padding-top: 10px to body, and remove the margin-top from your

    If you want to make a container that will prevent interior margins from collapsing beyond the bounds of the container, you'll either need to add padding or border to the container. If you don't want either of these visible features, you can add a negative margin and cancel it with positive padding. Like this:

    ...

    you could do the same thing on your body element if you want.

    Edit: here's your jsFiddle, updated to use the margin/padding trick on the body element

提交回复
热议问题