CSS Box Model
The CSS box model is a fundamental concept that describes the structure of elements in a web page. It consists of four areas: content, padding, border, and margin.
Components of the Box Model
-
Content:
- The actual content of the element (e.g., text, images).
- The size of the content can be controlled using
widthandheightproperties.
-
Padding:
- The space between the content and the border.
- Controlled using the
paddingproperty.
-
Border:
- The edge surrounding the padding.
- Controlled using the
borderproperty.
-
Margin:
- The space outside the border, separating the element from others.
- Controlled using the
marginproperty.
Example
div {
width: 200px;
height: 100px;
padding: 10px;
border: 2px solid black;
margin: 20px;
}
Visual Representation
The box model can be visualized as follows:
+-----------------------+
| Margin |
| +-----------------+ |
| | Border | |
| | +-----------+ | |
| | | Padding | | |
| | |+---------+| | |
| | || Content || | |
| | |+---------+| | |
| | +-----------+ | |
| +-----------------+ |
+-----------------------+
Box Sizing
The box-sizing property determines how the total size of an element is calculated.
-
Content-Box (default):
- The
widthandheightinclude only the content. - Padding and border are added outside.
- The
-
Border-Box:
- The
widthandheightinclude content, padding, and border.
- The
Example:
div {
box-sizing: border-box;
}