CSS Box Model Properties

ยท

2 min read

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 ๐Ÿ‘‡

css1.png A website with no margin or padding

But if you use the box model properties correctly, your website will look like this ๐Ÿ‘‡

css2.png 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. ๐Ÿ‘‡

css3.png

2nd box-model layer: Padding

The next layer of the CSS box model is the padding layer. It wraps our content like this ๐Ÿ‘‡

css4.png

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

css7.png

3rd box-model layer: Border

The next layer of the CSS box model is the border layer. It wraps our content + padding like this ๐Ÿ‘‡

css5.png

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

css8.png

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 ๐Ÿ‘‡

css6.png

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

css9.png

Finally, you can open the console and see the box model calculations:

css10.png

ย