Every element that can be displayed is comprised of one or more rectangular boxes.
CSS box model typically describes how these rectangular boxes are laid out on a web page.
These boxes can have different properties and can interact with each other in different ways, but every box has a content area and optional surrounding margin, padding, and border.
The CSS box model is essentially a box that wraps around every HTML element, it consists of:
The image below illustrates the box model:
Explanation of the different parts:
The box model allows us to add a border around elements, and to define space between/around elements.
border: 25px solid lightgreen;
In order to set the width and height of an element correctly, you need to know how the box model works.
Usually when you set the width and height of an element using the CSS width and height properties, in reality you are only setting the width and height of the content area of an element. To calculate the full size of an element, you must also add padding, borders and margins.
Assume we want to style a <div> element to have a total width of 400px:
border: 5px solid gray;
Here is the calculation:
370px (width) + 20px (left + right padding) + 10px (left + right border) + 0px (left + right margin) = 400px
The total width of an element should be calculated like this:
Total Width: width + padding-left + padding-right + border-left + border-right + margin-left + margin-right.
The total height of an element should be calculated like this:
Total Height: height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom.
Beyond setting the width, height, border, padding and margin of boxes, there are following other properties available to change how they behave:
You will learn about these properties later in this tutorial.