I can't believe I'm even asking this, but apparently Monday morning isn't going well. Why am I getting a space between these two div
elements?
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<meta charset="UTF-8">
</head>
<body>
<div style="margin:0;padding:0;min-height:200px;background-color:#c00;"></div>
<div style="margin:0;padding:0;min-height:200px;background-color:#ccc;"><p>Hello</p></div>
</body>
</html>
jsFiddle Example
This is due to collapsing margins. In short, the margin-top
of the p
element is causing the space between the div
elements. To fix this, you can set margin-top
of the p
element to 0
(example). If you still want space above the text in the p
element, you can set padding-top
to something (example). Alternatively, you can also set the padding-top
of the div
to something other than 0
, which will then use both the padding-top
of the div
and the margin-top
of the p
(example). A little hack to avoid collapsing margins and additional space at the top of the div
is to set a value to padding-top
that computes to 0
(example).
For more information, see the Collapsing Margins section of the CSS 3 specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With