Why Learn the Box Model?
If you are confused by the many adjustable spaces on a web page or are new to CSS, I highly recommend understanding the concept of the CSS box model first. Only by understanding how the box model works can you learn more web layout techniques.
Building Web Pages with Many Boxes
Web elements are like many boxes nested within each other.
To give a simple example, each HTML element is like a box with a start and an end. Each HTML tag (or DOM element) has properties related to layout, which can be explained as follows, from the inside out:
Content
Typically consists of some text content, other elements, or fixed width and height. For example, setting the width and height to 100px
creates a content space for that element.
Padding
Outside of the content is the padding, which allows you to set how much space to leave outside the content without changing the content itself. Clearly specifying how much space to reserve outside the content helps us create a model for content separation, making it much easier when writing responsive web pages, as you won’t have to consider the padding size when writing element sizes.
Border
Add a border to the element, noting that the border is also included in the element’s dimensions.
Margin
Whitespace that pushes outward, very similar to padding, but the difference is that margin is not included in the element’s dimensions.
Additional Knowledge
Now you understand what the CSS box model is! Here are some additional features related to it that you should pay attention to.
Margin Collapse
Adjacent elements in HTML can cause margin collapse, meaning that the margins of both will offset each other, leaving the larger margin as the main one.
You will notice that in the example above, there is only a 40px
margin between the two adjacent elements, which is what is known as margin collapse! Additionally, it is important to note that if you use layout methods like flex
, grid
, etc., which are not in the normal document flow, this feature will not exist.
Box Sizing Property
box-sizing
is a CSS property used to change the calculation method of the box model, specifically with two options:
content-box
- The size of the content is equal to the width and height properties. By default, all elements use this method for calculation.border-box
- The size of the content is equal to the width and height properties plus the padding and border.
Conclusion
- Content - The content of the element
- Padding - The space pushed inward
- Border - The border of the element
- Margin - The space pushed outward
The box model is one of the most important core concepts in CSS, and learning it will greatly help you with layout and calculations. If you need to revisit this knowledge after reading this article, you can open the browser’s developer tools, which provide convenient visual guidance for reference during development.
References
CSS Box Model - Web Dev Simplified Blog