The CSS Box Model

Understanding the CSS box model is important before you start designing elements in HTML. Every element in HTML is a rectangular box. This box contains properties like margin, border, padding and content.

So while we calculate the size of the box, we need to consider all 4 properties of the box model. You can get a clear picture of the box model from the below diagram.

box-model-css

Properties of Box Model

  • Margin – The spaces present around the element, outside the element’s border.
  • Border – The border present around the element.
  • Padding – The spaces present around the element, inside the element’s border.
  • Content – The actual content of the box like text/images etc.

Width and Height

When we set width and height of an element, it only applies to the content area. So if we calculate the total size of the element, we will add the width/height property with the margin, border and padding values.

<div class="box-element"> Some Content </div>
.box-element {
     width: 200px;
     height: 100px;
     margin: 20px 10px;
     padding: 10px;
     border: 2px solid black;
}

Here the total width =

width + padding-left + padding-right + border-left + border-right + margin-left + margin-right

= (200 + 10 + 10 + 2 + 2 + 10 + 10) px

= 244px

Same way, total height =

height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom

= (100 + 10 + 10 + 2 + 2 + 20 + 20) px

= 164px

The box-sizing property

The box-sizing property is used to control the CSS box-sizing behavior i.e. how the box size will be calculated.

Content-box

If we set box-sizing to “content-box”, it sets the default box-sizing behavior. That means the total size of any element will be calculated by considering the width/height plus the margin, border and padding properties.

Border-box

If we set the box-sizing to “border-box”, it calculates the total size of the element by considering only the width and height properties of the element. The browser won’t consider the margin, border or padding values in total size.

The box-sizing property is very much useful in sizing the elements.

Hope you have got a clear picture of box-modal and how to calculate the total width and height of an element. You have also got an idea about the usage of box-sizing property.

Leave a Reply

Your email address will not be published. Required fields are marked *