Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there white space appearing between two divs that don't have margins?

Tags:

html

css

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

like image 219
user875293 Avatar asked Jan 16 '12 17:01

user875293


1 Answers

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.

like image 141
0b10011 Avatar answered Oct 15 '22 00:10

0b10011