I encountered a strange behavior of nested div-blocks
, which I wonder how it can be explained logically and how to avoid.
My minimalized HTML
to demonstrate the behavior is as follows:
body{
padding: 0px;
margin: 0px;
background-color:gray;
}
#block1 {
height: 70vh;
width: 100vw;
position: fixed;
top: 0px;
padding: 0px;
margin: 0px;
background-color:cyan;
display: inline-block;
}
#block2{
height:40%;
background-color:green;
/* the following lines actually have no effect
padding: 0px;
margin: 0px;
position: relative;
top:0;
*/
}
#block3{
background-color:yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demonstrate Strange CSS Behavior</title>
</head>
<body>
<div id="block1">
<div id="block2">
<div id="block3">Hello!</div>
</div>
</div>
<!-- This html will add a space between block1 and block2
<div id="block1">
<div id="block2">
<div id="block3"><span><p>Hello!</p></span></div>
</div>
</div>
-->
<!-- This simple space will remove it again
<div id="block1">
<div id="block2">
<div id="block3"><span><p>Hello!</p></span></div>
</div>
</div>
-->
</body>
</html>
Because there is no padding and margin the div
blocks neatly overlap each other.
Demonstration with JSFiddle
When however a p-tag is wrapping the "Hello!" everything becomes strange. A space of about 10px
height appears between block1 and block2.
See JSFiddle here
This behavior does not show with an inline tag such as span, but it reappears with any block child node. And even more strange, when a non-breakable space is added after block2, the space between block1 and block2 is gone.
See in this JSFiddle
How can a so distant child change the spacing between grand(grand...) parents?
Update: Having studied similar QA threads and the discussion about CSS Reset, I arrived at the conclusion that CSS margin property is buggy and better avoided.To circumvent such problems use CSS reset code and positioning.