The follwoing html document has two divs, one with a border (id='with') and one without (id='without). The div with the border is rendered (at least on firefox and chrome) significantly higher than the one with the border.
I had expected them to vary at most 2 pixels in height, yet, the alert tells me that their height is 19 pixels different.
I can’t figure out why that is.
<!DOCTYPE HTML>
<html>
<head>
<title>Height of divs with/without a border</title>
<script type="text/javascript" src='jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
alert($('#with' ).height() + ' / ' +
$('#without').height());
});
</script>
</head>
<body>
<div style='width:300px;border:black 1px solid;background-color:yellow' id='with'>
<h1>With a border</h1>
bla<br>
bla<br>
bla<br>
</div>
<div style='width:300px;background-color:green' id='without'>
<h1>Without a border</h1>
bla<br>
bla<br>
bla<br>
</div>
</body>
</html>
By default, the
<h1>element has a top and bottom margin and these margins are collapsed. There are rules about how the margins are collapsed (i.e. combined). The rule that applies to your example is:In your example, the rule can be read as:
div#withoutdoes not have a border, its top margin (which is 0) is collapsed with the top margin ofh1(which is ~20px). The collapsed margin ends up outside the div. This means that these 20px do not add to the height of div.div#withhas a border, so the top margin ofh1(which is ~20px) is rendered inside the div, making it 20px taller than expected.