Today we're going to learn how to use the CSS box model. This will help you make pixel perfect websites and will teach you to use the margin, padding, and border properties more accurately.
Why learn CSS Box Model?
If you don't use them, your website will look like this ๐
A website with no margin or padding
But if you use the box model properties correctly, your website will look like this ๐
Same image of website with padding and good use of other box model properties
Much more visually appealing, right? If you want to make your website with accurate calculations, like the one above ๐ then this topic is for you. Learning about the CSS box model is one of many ways that will help you make pixel perfect websites.
CSS Box-Model Diagram
Think of the CSS box-model like an onion. It has 4 Layers:
- 1st layer: Content
- 2nd layer: Padding
- 3rd layer: Border
- 4th layer: Margin
1st box-model layer: Content
In HTML, everything behaves like a box. Let's insert some content with a kitty image. ๐
2nd box-model layer: Padding
The next layer of the CSS box model is the padding layer. It wraps our content like this ๐
How to use the padding property in CSS
This is the shorthand for the four padding properties:
- padding-top
- padding-right
- padding-bottom
- padding-left
3rd box-model layer: Border
The next layer of the CSS box model is the border layer. It wraps our content + padding like this ๐
How to use the border property in CSS
There are three crucial inputs of the border property:
- border size
- border style : solid / dotted/ dashed
- border color
4th box-model layer: Margin
The next and final layer of the CSS box model is the margin layer. It wraps our content + padding + border like this ๐
How to use margin property in CSS
This is the shorthand for the four properties of the margin property:
- margin-top
- margin-right
- margin-bottom
- margin-left
Finally, you can open the console and see the box model calculations: