Box Model in CSS
๐งฑ Box
Model in CSS
The CSS Box
Model is the fundamental structure that wraps every HTML element. It
defines how elements are displayed and how spacing is calculated.
Each element is essentially a box consisting of the following areas
(from innermost to outermost):
๐ฆ 1. Content
The actual content like text, images, or other
HTML inside the element.
width:
200px;
height:
100px;
๐ 2. Padding
The space inside
the element, around the content. It pushes the content away from the edges of
the element.
padding:
10px;
/* space between content and border */
๐ผ️ 3. Border
The line surrounding the padding (and content).
border:
2px solid black;
๐ 4. Margin
The space outside
the border, creating space between elements.
margin:
20px;
/* space between elements */
Visual Representation of the Box Model:
|<
----------- Margin ----------->|
| |<
-------- Border -------->| |
| | |<
----- Padding ----->| | |
| | | | Content | | |
| | |<
------------------->| | |
| |<
------------------------->| |
|<
------------------------------->|
๐งฎ Box Model Dimensions Formula
To calculate the total space an element takes
up:
Total Width = margin + border + padding + content width
Total Height = margin + border + padding + content height
Use the box-sizing
property to control how this
calculation works:
box-sizing: content-box;
/* Default: padding & border added outside width */
box-sizing: border-box;
/* Includes padding & border within width */
๐งช Example:
<div
style=
"width: 300px; padding: 20px; border: 5px solid blue; margin: 30px; box-sizing: border-box;">
This is a box
</div>