Every HTML element on a web page can be thought of as a rectangular box. The CSS Box Model is a fundamental concept that describes how these boxes are rendered and how their dimensions, spacing, and borders are calculated. Understanding this model is crucial for precise layout and styling of web pages.
The Core Components
The CSS Box Model consists of four main parts, layered outwards from the content:
- Content: This is the actual text, images, or other media within an element. Its dimensions are determined by the `width` and `height` properties.
- Padding: The space between the content and the border. It's transparent and can be controlled using `padding`, `padding-top`, `padding-right`, `padding-bottom`, and `padding-left`.
- Border: A line that surrounds the padding and content. It's controlled by `border`, `border-width`, `border-style`, and `border-color`, or their individual sides.
- Margin: The space outside the border, separating the element from other elements. It's also transparent and controlled by `margin`, `margin-top`, `margin-right`, `margin-bottom`, and `margin-left`.
Box Sizing: `content-box` vs. `border-box`
By default, the `box-sizing` property is set to content-box. This means that if you set a `width` and `height`, those values only apply to the content area. Padding and border are added *on top* of that, increasing the total space the element occupies.
However, it's often more intuitive to use border-box. When `box-sizing: border-box;` is applied, the `width` and `height` properties include the content, padding, and border. This makes it much easier to manage element dimensions.
Experiment with Box Sizing
Set the content dimensions and see how padding and border affect the total size.
For a different perspective on web design, explore the gradient generators.