margin-top in a nested div

前端 未结 6 1811
失恋的感觉
失恋的感觉 2020-12-04 21:52

I have a problem with the margin-top in a nested div -- when I apply margin-top to the nested div, the margin is applied to the parent div inst

6条回答
  •  -上瘾入骨i
    2020-12-04 22:33

    The reason overflow:auto changes the parent div to allow the nested margin-top is that it creates a new formatting context. Any div that's positioned absolute, fixed, floated or with overflow other than visible creates a new formatting context. The parent div then becomes the root of this new formatting context, and collapsing margins don't apply to root elements.

    More in depth:

    Formatting contexts can be either inline or block, and only the block formatting contexts collapse their margins. These formatting contexts form the flow of the document.

    A block formatting context is simply all the block level elements (e.g. divs, p, table) laid out one after another vertically within a containing block until the end of the document/container or until a new formatting context is established.

    In the case of nesting, the margin-top of the child collapses with the margin-top of the parent since both divs are part of a block formatting context. By setting overflow to auto, the parent div becomes the container of the new formatting context, and the child the first block element within it. Thus the two margins are no longer "adjoining" since the parent div is now the root.

    Hope that helps.

    Box model: http://www.w3.org/TR/CSS2/box.html#collapsing-margins

    Visual formatting model: http://www.w3.org/TR/CSS2/visuren.html#normal-flow

提交回复
热议问题