CSS Box Model Summary
The CSS box model is the way CSS controls the space around every HTML element. Each element can have content, padding, a border, and margin.
.box {
width: 300px;
padding: 20px;
border: 2px solid black;
margin: 20px;
}
Every Element Is A Box
Most HTML elements can be thought of as boxes. A paragraph is a box. A heading is a box. A div is a box. CSS decides how much space those boxes take up and how far apart they are from other boxes.
The box model is important because layout is mostly the work of sizing, spacing, and arranging boxes on a page.
Content
The content is the text, image, button, or other thing inside the element. When you set width or height in CSS, you are usually setting the size of the content area.
.box {
width: 300px;
}
Padding
Padding is space inside the box. It creates room between the content and the edge of the box.
.box {
padding: 20px;
}
Padding is commonly used to make text easier to read inside buttons, cards, sections, and other boxes.
Border
A border is a visible line around the box. Borders are often used to show the edge of a card, button, input, or section.
.box {
border: 2px solid black;
}
Margin
Margin is space outside the box. It pushes the box away from other elements.
.box {
margin: 20px;
}
Margin is commonly used to create space between headings, paragraphs, images, cards, and page sections.
Box Sizing
By default, width does not include padding or border. This can make boxes larger than expected.
The property box-sizing: border-box; makes width include the content, padding, and border. This usually makes layouts easier to control.
.box {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 2px solid black;
}
This is used very often because it makes the size of boxes easier to understand.