Margin From Heading Pushes Div Down
Solution 1:
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.
Solution 2:
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.
Post a Comment for "Margin From Heading Pushes Div Down"