Why are block level elements forcing a vertical scrollbar and blank space at the top?
The <h3>
in the following code is forcing a vertical scrollbar, which is, in turn, causing a blank space (it's red; i.e. the body
) at the top of the page.
Why?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" >
<title>Test</title>
<style type="text/css">
html { height: 100%; }
body {
background-color:#f00;
margin:0;
padding:0;
height:100%;
}
#divParent1 {
background-color:#0f0;
background-image:url("example1_bg.png");
background-repeat: repeat;
height:100%;
margin:0 auto;
padding:0;
}
#div1 {
background-image:url(example1_white_center.png);
background-repeat: repeat-y;
background-position: center;
width:1200px;
min-width:1200px;
_width:1200px;
height:100%;
margin:0 auto;
}
#div2{
background-image:url(example1_dgreen_blank.png);
background-repeat: no-repeat;
height:100%;
margin:0;
}
</style>
</head>
<body>
<div id="divParent1">
<div id="div1">
<div id="div2">
<div style="width:100%; position:relative; top:240px; margin:0;">
<div style="margin:0 auto; width:570px; background-color:#00f; ">
<h3>LOLOL</h3>
hi<br开发者_如何学Python>hi<br>hi<br>hi<br>hi<br>hi<br>hi<br>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Note: This result cannot be replicated on jsfiddle, making me even more confused.
So today you learn something new about HTML. Margins combine/collapse/merge. So the margin on the H3 element is combining with the margin on the body element, and giving the body element the margin.
See http://www.w3.org/TR/CSS21/box.html#collapsing-margins
You can add intervening elements (padding, border) to prevent this, or remove the margin from the H3 element.
This was done (I believe) because that's how the original P tag worked. Above and below the P tag was some space - but if you had two P tags one after the other, you did not get twice the space, but rather just once. In order to replicate this behavior when HTML switched to CSS they created 'margin', and made it combine.
精彩评论