CSS Box Model is the section 10 of Beginner’s Guide to CSS.
All HTML elements can be considered as boxes. What CSS do is, it wraps around these boxes. That what we are calling it as CSS box model.
The box model allows us to place a border around elements and space elements in relation to other elements. Look at the following figure. It shows the box model of our “What’s Next” Header Element.
You’ll see the following things in the box model.
- Content – The content of the box, where text and images appear. In the figure you see it in the blue colored area. That is our
header element where the text of “What’s Next” goes. The width and height of this
box is specified there. So each element has a width and a height creating the box model.
- Padding – Clears an area around the content. The padding is affected by the background color of the box. In our header element it doesn’t contain any padding.
- Border – A border that goes around the padding and content. The border is inherited from the color property of the box
- Margin – Clears an area around the border. The margin does not have a background color, it is completely transparent. You’ll see in our header element it contains 12px bottom margin.
Learning of box model is most important when we’re dealing with elements to create the layout of our web page.
Width and Height of the Box
When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add the padding, borders and margins.
Try to calculate the width a
border: 2px solid gray;
The calculation goes like this
+ 120px ( width )
+ 20px ( left padding )
+ 20px ( right padding )
+ 2px ( left border )
+ 2px ( right border )
+ 8px ( left margin )
+ 8px ( right margin )
When you calculating this kind of thing, always remember to add up both left and right sides of the property or top and bottom sides of the property.
This concept is coming handy when you use table and division tags. Anyway all the elements have box models that wraps by CSS properties. Learning CSS box model will be useful for you someday when you goes into some advanced concepts. In the next few sections we’re going through the CSS properties that wraps around the CSS Box Model.
Let’s learn how to Bordering with CSS.