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 in the CSS box modelCSS box modelBox model overview A box in CSS consists of a content area, which is where any text, images, or other HTML elements are displayed. This is optionally surrounded by padding, a border, and a margin, on one or more sides. The box model describes how these elements work together to create a box as displayed by CSS.https://developer.mozilla.org › Web › CSS › CSS_Box_ModelCSS Box Model - Cascading Style Sheets - MDN Web Docs, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen.
To avoid the width or height getting increased or decreased when using CSS properties like margin , padding , etc, we can use the CSS property called box-sizing and set its value to border-box on the element in CSS.
Yes, borders take up physical space. So, if you set a div to be 100%, then give it a 1px border, it will be 2px wider than the container it is in. To get around it, you can decide not to set a width at all (or 'auto') so that it will automatically adjust to account for padding and borders.
The border-width shorthand CSS property sets the width of an element's border.
It's because the top margin for the nested <h1 />
is contained when there is a border. Note @Elliott's fiddle doesn't work because the margins have been removed by jsfiddle's default settings.
EDIT: check this out for more infos http://reference.sitepoint.com/css/collapsingmargins
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