The box model
Every HTML element on the page is essentially considered a box. The box is a container that includes the element.
The box model sets the sizing of the elements based on a few CSS properties.
From the inside to the outside, we have:
The element itself
Padding between the element and the border
Border
Margin, between the border and the “outside”
The element can be sized by setting its width and height CSS properties:
Imagine those properties being set for a selector, like p {}
.
The width can be adaptive, meaning you can set a minimum width or maximum width:
Same for height.
Padding can be set using the padding
property, and its helpers padding-top
, padding-right
, padding-bottom
, and padding-left
:
The padding
property allows you to set a value for each side, using this syntax which sets the values of top-right-bottom-left:
And there’s a shortcut to set the values of top/bottom and left/right:
Margin can be set in the same way, using margin
and its helpers margin-top
, margin-right
, margin-bottom
, and margin-left
:
And you can use all the “tricks” we saw above to set top, right, bottom, and left values, or top/bottom and left/right.
The border
property can be used to set the border, along with its helpers border-top
, border-right
, border-bottom
, and border-left
.
It’s distinct from padding
and margin
:
You can also use dotted
and double
as the border style, along with other values.
Then, you can also set the color:
You can also just set one border:
And you can also set the properties individually:
The best way to visualize the box model is to open the browser DevTools and check how it is displayed. See? From the inside out, you have the elements listed:
Chrome
That was Chrome.
This is how it’s displayed in Firefox:
Firefox
Here you can see how the browser tells me the properties of an element I highlighted. I right-clicked an element, clicked “Inspect” or “Inspect Element”, and went to the “Computed” panel of the DevTools (Chrome) or “Layout” panel of the DevTools (Firefox).
Last updated
Was this helpful?