CSS Box Model

By Tony 8.2.2024


To really master spacing of elements, you need to first understand how CSS works. From width, height, padding, margin, and border, they're all connected to the CSS box model. Here, we'll explore what CSS box model is.

Every HTML element you have on a page has a CSS box model, and it has several components: content, padding, border, and margin. Let's say you have a normal element, a div, and you have some text inside it. The text is the content of the box (element). The padding you apply to the div is the padding of the box. The border of the box is the border, and the margin of the box is the margin. Pretty intuitive, right? Yeah, that's how simple the CSS box model is. The only tricky part is when you apply width and height. If you apply a width/height to the div, it sets the total width/height of the combination of padding + content to the width/height value. For example, if the div's text (content) has a width of 50px without padding/border/margin, and you apply a 20px padding on all four sides, then the total width of the element (box) will be 50 + 20 + 20 which is 90px. An element's margin and border does not count as part of the element's height or width.

In conclusion, the browser renders HTML elements' CSS styles according to the CSS box model, which contains the content, padding, border, and margin of an element. The actual width/height of the element is only composed of the width.height of the content plus the padding.