Box Model
How the box model works
Every element on the web is treated as rectangular boxes. To modify the size and position of an element, you can use the box model. It consists of four properties: margin, border, padding, and content.
The final width and height of an element is the width and height of its content box, plus the padding and borders width of its padding box.
div {
margin: 32px;
border-width: 8px;
padding: 24px;
height: 64px;
}
margin: 32px;
border-width: 8px;
padding: 24px;
height: 64px;
Hello world!
In this case, the height of the
<div>
element can be calculated as follow:
32px + 8px + 24px + 64px + 24px + 8px + 32px = 192px
¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
¦ ¦ ¦ height ¦ ¦ ¦
¦ ¦ ¦ ¦ ¦ ¦
¦ ¦ padding––––padding ¦ ¦
¦ ¦ ¦ ¦
¦ border––––––––––––––––––border ¦
¦ ¦
margin––––––––––––––––––––––––––––––––margin
Advanced: changing the box model
The
box-sizing
property is used to change the default box model. By setting it to
box-sizing: content-box;, the specifyied width and height of the element includes the
padding and borders, which, in this case, would result in a total
height of 128px
32px + 64px + 32px = 128px
¦ ¦ ¦
¦ /––––––––––––¦––––––––––––\ ¦
¦ ¦ ¦ ¦ ¦ ¦ ¦
¦ 〔8px + 24px + 0 + 24px + 8px〕 ¦
¦ ¦ ¦ ¦ ¦ ¦ ¦
¦ ¦ ¦ height ¦ ¦ ¦
¦ ¦ ¦ ¦ ¦ ¦
¦ ¦ padding–padding ¦ ¦
¦ ¦ ¦ ¦
¦ border–––––––––––––––border ¦
¦ ¦
margin–––––––––––––––––––––––––––––––margin