CSS Box Model
In HTML and CSS, every single element on the web page is treated as a rectangular box. The CSS Box Model explains how these boxes are structured and how they interact with one another.
The Layers of the Box
The Box Model consists of four distinct layers, starting from the inside out:
- Content: The actual text, image, or child elements. Its size is controlled by
widthandheightproperties. - Padding: The transparent inner spacing between the content and the border. It adopts the element's background color.
- Border: A line that goes around the padding and content. You can style its thickness, type (solid, dotted), and color.
- Margin: The transparent outer spacing that pushes other elements away. Margins do not have background colors.
The Problem with Default Sizing
By default, CSS applies box-sizing: content-box. This means that if you set a box to have a width of 200px, and then add 20px of padding and a 5px border on each side, the total actual width becomes 250px (200 + 20 + 20 + 5 + 5). This makes precise layout calculations very difficult.
The Border-Box Solution
To fix the sizing issue, modern web development relies on box-sizing: border-box. When you apply this property, setting a width: 200px guarantees that the element will be exactly 200px wide, including padding and border. The content area will simply shrink to accommodate them.
It is highly recommended to include a global reset at the top of your CSS:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}Advanced Margin Collapse+
When vertical margins of two adjoining block elements touch, they combine (or "collapse") into a single margin. The size of the collapsed margin is equal to the largest of the two margins. Note that horizontal margins do not collapse, and margins do not collapse for flex or grid items.
