The CSS Box Model

The CSS box model describes the display of objects in a web page. According to this, everything that is displayed is inside a rectangular box. Web browsers generate such rectangular boxes for every HTML elements, for example: divs, paragraphs, tables, images etc. Such a box consists of margins, borders, padding, and the actual content of the element.

css box model

You can think of this as several boxes in a box.

The outer region of the box is called the margin. The border is the outermost area of the element. The padding adds space between the content and the border.

Or, explained in a different way, you have the actual content and it has three layers. A padding, a border and a margin. The width of all three can be 0.

The border, the margin and padding are called properties. Since all elements have these properties they all affect the layout of the page.

Since you can place a box within another box, the dimensions of the inner box is limited by the outer box. You can think of the body as such a box. It limits or controls the dimensions (width, height) of the other elements inside of it.

The padding, border and margin can be divided into top, bottom, left and right.

CSS Box model – Sizing

The width of the box can be calculated easily. It is the sum of the width of the content, the size of the left and right padding, the size of the left and right border and the margin.

Take a look at this css code:

p {
   background-color: lightblue;
   width: 200px;
   padding: 15px;
   border: 2px solid red;
   margin: 0;
}

The width of the paragraph is 200px, but this is not the total width of this element because it has padding and border as well.

So the actual size is: 200px + 15px (left padding) + 15px (right padding) + 2px (left border) + 2px (right border) + 0px (left, right margin)

The total width of this element is 234px

The height can be calculated the same way we just need to take the height and top and bottom paddings, borders and margins.

ChristianKovats
ChristianKovats

Christian Kovats is a London-based web designer who loves crafting innovative and user-friendly interfaces. His passion for design is only rivaled by his love for nature and hiking, often drawing inspiration from his treks through the diverse landscapes of the UK. Outside of work, Christian enjoys spending quality time with his wife and 4-year-old son. A seasoned lucid dreamer, he also spends time exploring the intricate world of dream interpretation, reflecting his ever-curious and creative mind.

ChristianKovats

Leave a reply

You must be logged in to post a comment.