Margin adds space outside an element. It keeps elements from touching each other.
0
0
Margin in CSS
Introduction
To separate paragraphs so they don't stick together.
To add space around images so text doesn't crowd them.
To create breathing room between buttons on a page.
To push content away from the edges of the browser window.
To control layout spacing without using empty elements.
Syntax
CSS
margin: <top> <right> <bottom> <left>;You can use 1 to 4 values:
- 1 value: all sides same margin
- 2 values: vertical | horizontal
- 3 values: top | horizontal | bottom
- 4 values: top | right | bottom | left
Use units like rem, em, %, or px (avoid px for better scaling).
Examples
All four sides get 1rem margin.
CSS
margin: 1rem;
Top and bottom get 1rem, left and right get 2rem.
CSS
margin: 1rem 2rem;
Top 1rem, left and right 2rem, bottom 3rem.
CSS
margin: 1rem 2rem 3rem;
Top 1rem, right 2rem, bottom 3rem, left 4rem.
CSS
margin: 1rem 2rem 3rem 4rem;
Sample Program
This example shows two blue boxes stacked vertically. The margin on the boxes adds space around them: 2rem on top, 4rem on right, 1rem on bottom, and 0 on left. This spacing keeps the boxes from touching each other or the page edges.
CSS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Margin Example</title> <style> body { font-family: Arial, sans-serif; padding: 2rem; background-color: #f0f0f0; } .box { background-color: #4a90e2; color: white; padding: 1rem; margin: 2rem 4rem 1rem 0; border-radius: 0.5rem; } </style> </head> <body> <div class="box">This box has margin: 2rem 4rem 1rem 0;</div> <div class="box">This box has the same margin, so it is spaced nicely.</div> </body> </html>
OutputSuccess
Important Notes
Margin does not add color or background; it just creates empty space.
Negative margin values can pull elements closer or overlap them, but use carefully.
Margins collapse vertically between elements, meaning adjacent vertical margins combine into one.
Summary
Margin adds space outside elements to separate them.
You can set margin for all sides at once or individually.
Use margin to control layout spacing without extra HTML elements.