CSS Box Model
5. CSS Box Model
5.3. Listing 5.5.3
Remember that when you specify the width, by default, it sets the width of the content of the element not the element box. Thus, in Listing 5.5.2 the total width of the element is the sum of the left
and right border and padding and the width of the content which is 430px. This is because the box-sizing property of this element is set to content-box. But if the box-sizing property is set to border-box (see Listing 5.5.3), the sum of the left and
right border and padding and width of the content will be equal to 300px (see Figure 5). This is important especially in creating the layout of the web page. Basically, you might want to do this to all your HTML elements. Instead of adding the property
box-sizing in all the elements, you can use the universal selector and add the style rule for box-sizing.
Listing 5.5.3 Box Border Example with box-sizing set to border-box
<!DOCTYPE html>
<html>
<head>
<style>
* {
box-sizing: border-box; /* inclusion of box-sizing */
}
div {
background-color: lightgrey;
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<div>This text is the content of the box. We have added a 50px padding,
20px margin and a 15px green border.
</div>
</body>
</html>

Figure 5. Output of Listing 5.5.3 when box-sizing is added