margin from heading pushes div down

混江龙づ霸主 提交于 2019-12-02 13:51:20
Seth

Try adding overflow:auto to the parent element.

CSS: Margin-top when parent's got no border

You can also use overflow:hidden. Using the overflow attribute on a parent element will also clear inner floats making clear:both not necessary.

Note:

This is a new answer to this question because margin on element moves the whole page down was marked as a duplicate of this question, but I don't feel the accepted answer explains why this is happening, so here is a more detailed explanation of why you sometimes have a parent element have an odd, unexplained gap if the first child has a collapsed margin.

Answer:

This is because of the Block Formatting Context (Also here). basically what you're seeing is collapsing margins in action. Collapsing margins are supposed to help collapse text based elements together so you don't have doubled up margins on things like paragraphs and headings, but the problem is that it's collapsing the paragraph to the parent causing the parent to effectively adopt the paragraph's margin:

Parent and first/last child If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of its first child block; or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
Mastering margin collapsing - MDN

One solution to your problem would be to create a new Block Formatting Context on the parent. You can do this easily be adding overflow: auto to the parent. It's likely that the parent element doesn't have a set height, so it shouldn't affect the document visually. All it will do is create a new context that will cause the margin of the first child to be contained in the parent.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!