Why HTML Element Has Space Or Gap On Top
CSS
26/12/2022
You may encounter a situation where an HTML element appears to be offset at the top, even though no top margin was set. You, my friend, have just experienced margin collapse! 👻
Here's a (personal) example: you've got a body
element which for some reason has an offset at the top, with no visible margin upon inspection in the browser.
It turns out that the offset comes from the child element inside the body. How is this happening? 🤷♀️
In CSS, when the vertical margins of two block elements meet, the largest margin out of these two is used instead of combining them.
How does this relate to the stated example problem?
As it stands, there is no padding or element with height at the very top of the body
element preventing the top margin of the div
tag touching the top margin of the body
. This causes both margins to collapse 💥 and have the larger margin from the div
stick out of the parent element.
Solution(s)
This problem can be solved by either:
- Not setting a top margin for the
div
, or - Adding a top padding to the
body
.