box model

testYourselfCSS CSS197 0 0

Each HTML element is represented as a rectangular box, with the box's content, padding, border, and margin.

The model determines how the different parts of the box - margin, border, padding, and content - work together to form a box that you can see on the page. The full CSS box model applies to block boxes. 

in CSS box model consists of:

  • content box - the area where your content is displayed
  • padding box
  • border box
  • margin box

There are two types of box models:

  • standard box model
  • alternative box model

We can switch between box models by using box-sizing CSS property. This property defines how the browser should calculate the total width and height of a box.

Standard box model (content-box)

In the standard box model, if you give a box a width and a height attribute, this defines the width and height of the content box. Any padding and border is then added to that total width and height to get the total size taken up by the box. Therefore the final width and height can be grater than the width and height that we specified in the css styles.

content width = css width

content height = css height

total width = css width + border + padding

total height = css height + border + padding

Alternative box model (border-box)

CSS had an alternative box model introduced some time after the standard box model. Using this model, the total width and height are the width and height specified in css styles, therefore the content area width is that width minus the width for the padding and border.

content width = css width - border - padding

content height = css height - border - padding

total width = css width

total height = css height

It doesn't matter if we use the content-box or the border-box, the margin is never included in the final width or height.

Content-box vs Border-box

css:

.box {
  width: 100px;
  height: 100px;
  border: 5px solid black;
  padding: 20px;
}

#box1 {
​​​​​​​  background: red;
​​​​​​​  box-sizing: content-box;
}
#box2 {
​​​​​​​  background: yellow;
​​​​​​​  box-sizing: border-box;
}

html:

<div class="box" id="box1">CSS is awesome</div>
​​​​​​​<div class="box" id="box2">CSS is cool</div>

result:

CSS is awesome
CSS is cool
 

box1:

content width/height = 100px

total width/height = 150px (100px + 2 * 20px + 2 * 5px)

box2:

content width/height = 50px (100px - 2 * 20px - 2 * 5px)

total width/height = 100px