Box Model
A really important thing to remember when writing CSS, or working on the web as a whole, is that everything displayed by CSS is a box. Whether that’s a box that uses
border-radius
to look like a circle, or even just some text: the key thing to remember is that it’s all boxes.
Boxes have different behavior based on their
display
value, their set dimensions, and the content that lives within them.
This content could be even more boxes—generated by child elements—or plain text content. Either way, this content will affect the size of the box by default.
When you switch to intrinsic sizing, you are letting the browser make decisions for you, based on the box’s content size. It’s much more difficult for there to be overflow with intrinsic sizing because our box will resize with its content, rather than try to size the content. It’s important to remember that this is the default, flexible behavior of a browser. Though extrinsic sizing gives more control on the surface, intrinsic sizing provides the most flexibility, most of the time.
You start with content box, which is the area that the content lives in. As you learned before: this content can control the size of its parent, so is usually the most variably sized area.
The padding box surrounds the content box and is the space created by the
padding
property. Because padding is inside the box, the background of the box will be visible in the space that it creates. If our box has overflow rules set, such asoverflow: auto
oroverflow: scroll
, the scrollbars will occupy this space too.
The border box surrounds the padding box and its space is occupied by the
border
value. The border box is the bounds of your box and the border edge is the limit of what you can visually see. Theborder
property is used to visually frame an element.
The final area, the margin box, is the space around your box, defined by the
margin
rule on your box. Properties such asoutline
andbox-shadow
occupy this space too because they are painted on top, so they don’t affect the size of our box.