CSS Box Model: Cheat Sheet
CSS Box Model: Cheat Sheet
Margin
Border
Padding
Content
Padding
The space between the content and the border of an element
Set the padding on all sides
padding: 5px Set the padding to 5px on all sides
Set the padding on the top side, horizontal axis, and bottom side
padding: 5px 2px 3px Set the padding to 5px on the top, 2px on the left and right, and 3px on the bottom
Border
The divider between the padding of an element and its margin
Set the border-width, border-style, and border-color
d : 5px
bor er sol id a
bl ck Set the border to a 5px wide solid black line
The margin of elements can collapse meaning only the largest margin will be used to space out elements
Set the margin on the top side, horizontal axis, and bottom side
margin: 5px 2px 3px Set the margin to 5px on the top, 2px on the left and right, and 3px on the bottom
b
margin- ottom: 3px
Set the margin on the bottom
Set the margin to 3px on the bottom
Box Sizing
Determines how the size of the content of an element is calculated when a width/height is given
The width and height properties of an element specify the exact size of the
content of the element and do not include the border, padding, or margin
box-sizing: content-box This is the default value in CSS. If an element has a width of 50px and a padding of 10px on all sides
then the element will be a total of 70px (50px from the content width and 10px from both the left
and right side padding ). This is somewhat conterintuitive which is why I generally recommend not
using content-box.
box-sizing: border-box If an element has a width of 50px and a padding of 10px on all sides then the element will be a total
of 50px. The content portion of the element will only be 30px wide, though, since that is the
remaining space after the 10px of padding are applied to This makes sizing elements much easier
which is why I generally recommend always using border-box.
Display
Determines how an element is laid out on a page
Elements will span the entire width of their container and begin on a new
display: block line after the previo us content
Block elements by default will be on their own line and push everything else onto the next line. Block
elements also can have a specific width or height set.
Elements will take up only the amount of space needed to fit the content
display: l
in in e inside them
Inline elements by default will not take up any more space than they need to. Inline elements also
cannot have a specific width or height set since their size is based on the size of the content in them.
Elements will take up only the amount of space needed to fit the content
display: l
in in - e block inside them, b ut a manual width or height can be set
Inline block elements by default will not take up any more space than they need to. Inline block
elements also can have a specific width or height set which overrides the default size of the element.