I have the following code:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Modelo Cajas</title>
<style type="text/css">
#contenedor{
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
border:solid 2px;
}
#interno{
height: 100%;
padding: 20px;
border: dashed 10px red;
}
</style>
</head>
<body>
<div id="contenedor">
<div id="interno"></div>
</div>
</body>
</html>
I don't understand why the "inner" div exceeds the "container" div in height. I suspect it may be because of the height property but I don't understand why this effect occurs. Thank you
It has to do with ownership
box-sizing
. By default, it is set tocontent-box
, which means that if you assignwidth
yheight
, it will be assigned to the content regardless of paddings and borders. Which means that the height of your "box" will be.
If you want this not to happen, set
border-box
to thebox-sizing: border-box;
. This will make the height and width you define, include the border and padding. So it will be as follows;The default value is content box . This is very important as it alters the way you calculate both the width and height of your boxes.
The rule is simple. If you use content box the width of your boxes will be: left margin + left border + left padding + width + right padding + right border + right margin. The same rule would apply for height.
If you use box padding, you don't have to recalculate the width of your boxes if you use padding, however you do when you use borders and margins.
Finally in border box we would only have to be aware of the margins. Border-box is currently used as a good practice, since it avoids you recalculating the size of your boxes if you add the aforementioned properties.