CSS
π― What is Margin?
Margin is the space outside an elementβs border.
It controls how far an element stays away from surrounding elements.
π§© Simple Definition
Margin = Outer spacing around an element
π‘ Visual Representation
+----------------------------------+
| Margin |
| +----------------------------+ |
| | Border | |
| | +----------------------+ | |
| | | Padding | | |
| | | +----------------+ | | |
| | | | Content | | | |
| | | +----------------+ | | |
| | +----------------------+ | |
| +----------------------------+ |
+----------------------------------+
π The margin is the outer area around the element.
It creates spacing between elements.
π§ Basic Usage
margin: 20px;
This adds 20px of space to all sides:
- top
- right
- bottom
- left
πΉ Setting Margin for Individual Sides
You can define margin separately for each side.
Individual Properties
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
Shorthand Property
margin: 10px 20px 30px 40px;
π Order:
top β right β bottom β left
βοΈ Accepted Values
| Value Type | Description |
|---|---|
| length | Uses fixed units like px, em, rem |
| % | Percentage of parent element width |
| auto | Browser automatically calculates margin |
| initial | Resets to default value |
| inherit | Inherits value from parent element |
π§© Using auto
The auto value is commonly used for centering elements.
β Example
.box {
width: 300px;
margin: 0 auto;
}
π Explanation
- 0 β top and bottom margin
- auto β left and right margins are automatically calculated
π This centers the element horizontally.
π§© Practical Example
<div style="width:300px; margin:0 auto; border:2px solid black;">
This box is centered.
</div>
β οΈ Difference Between Margin and Padding
| Feature | Margin | Padding |
|---|---|---|
| Location | Outside the element | Inside the element |
| Purpose | Creates space between elements | Creates space between content and border |
| Affects | Outer spacing | Inner spacing |
π Example: Margin + Padding Together
<div style="background:lightblue; margin:30px; padding:10px; border:2px solid navy;">
This box has:
- 30px margin
- 10px padding
</div>
π§ Explanation
margin: 30px;
Creates 30px of outer space around the element.
padding: 10px;
Creates 10px of inner space between the content and the border.
π― Margin Collapsing
Vertical margins can sometimes collapse into each other.
Example
h1 {
margin-bottom: 20px;
}
p {
margin-top: 30px;
}
π Instead of 50px, the browser may only use the larger margin (30px).
This behavior is called:
Margin Collapsing
π§ In Summary
margin controls the outer spacing of an element
It creates distance between elements
IIt can be applied to all sides or individually
auto is commonly used for horizontal centering
Margin is an important part of the CSS box model
