CSS Box Model

·

2 min read

What is the CSS box model?

Every element (text, image, icon) on a web page can be considered a box. The box consists of the following areas:

  • Content
  • Padding
  • Border
  • Margin

boxmodel.gif

Content - It can be text or an image.

Padding - Space between content and border.

Border - It surrounds content and padding.

Margin - Space around the border.

To style an HTML element with CSS, we play around with these properties of a box model.

Determining the width and height of an element

By default when we set the width and height of an element, we are actually setting the width of the content box.

When the browser renders this element on the screen, it includes a border and padding with the content box's width and height.

Let's understand this with an example.

css model.png

<!DOCTYPE html>
<html lang="en">
  <head>
     <style>
        .box1{
          width: 50px;
          height: 50px;
          background-color: blue;
        }
        .box2{
          width: 50px;
          height: 50px;
          padding: 5px;
          background-color: green;
          border: 5px solid black;
        }
     </style> 
  </head>
  <body>
    <div class="box1"></div>
    <div class="box2"></div>
  </body>
</html>

You can see that both the green and blue box has the same width and height, but the green box is bigger than the blue box.

How does the browser calculate width and height?

Total width = left-border-width + left-padding + content-width + right-padding + right-border.

Total height = top-border-width + top-padding + content-height + bottom-padding + bottom-border.

It seems a little strange, isn't it? We set the same dimensions for two elements, but they appear different.

How to make dimensions consistent?

CSS provides a property: box-sizing. It can help us here.

The box-sizing property can be set to -

box-sizing: border-box;
or
box-sizing: content-box;

By default, box-sizing is set to content-box.

When you set box-sizing to border-box, the browser shrinks the content-box size to absorb the border and padding dimensions.

Let's use this property in the above example.

css model2.png

  <style>
        .box1{
          width: 50px;
          height: 50px;
          background-color: green;
        }
        .box2{
          width: 50px;
          height: 50px;
          padding: 8px;
          background-color: blue;
          border: 5px solid black;

          box-sizing: border-box;  

        }
     </style>