The margin
property in CSS is used to create space around elements, outside their border. It helps control the layout and spacing between elements on a webpage.
Syntax
You can set margins using the shorthand margin
property or individual margin properties:
/* Shorthand property */ margin: top right bottom left; /* Individual properties */ margin-top: value; margin-right: value; margin-bottom: value; margin-left: value;
Values
- Length:
- Specifies a fixed margin size using units like
px
,em
,rem
,%
, etc. - Example:
margin: 20px; /* 20px on all sides */
- Specifies a fixed margin size using units like
- Percentage:
- Calculates the margin as a percentage of the containing element’s width.
- Example:
margin: 10%;
- Auto:
- Automatically adjusts the margin, often used for centering elements horizontally.
- Example:
margin: 0 auto; /* Centers the element horizontally */
- Inherit:
- Inherits the margin value from the parent element.
- Example:
margin: inherit;
Shorthand Property
The margin
shorthand can accept 1 to 4 values:
- One value:
- Applies to all four sides.
- Example:
margin: 10px;
- Two values:
- First value: Top and bottom.
- Second value: Left and right.
- Example:
margin: 10px 20px;
- Three values:
- First value: Top.
- Second value: Left and right.
- Third value: Bottom.
- Example:
margin: 10px 20px 30px;
- Four values:
- Applies to top, right, bottom, and left in clockwise order.
- Example:
margin: 10px 20px 30px 40px;
Examples
Basic Margin
<div style="margin: 20px; background-color: lightblue;">Box with margin</div>
Different Margins for Each Side
<div style="margin: 10px 15px 20px 25px; background-color: lightgreen;"> Box with specific margins </div>
Centering an Element
<div style="width: 200px; margin: 0 auto; background-color: lightcoral;"> Centered Box </div>
Using Percentage Margins
<div style="margin: 5% 10%; background-color: lightgoldenrodyellow;"> Box with percentage margins </div>
Negative Margins
Margins can have negative values, which pull the element closer to its neighboring elements.
<div style="margin: -10px; background-color: lightpink;"> Box with negative margin </div>
Best Practices
- Avoid Overlapping Margins:
- Adjacent vertical margins between elements can collapse (merge into one margin).
- Example:
div { margin: 20px; }
Two stacked
div
elements will have a total margin of 20px, not 40px.
- Use
auto
for Centering:- Horizontal centering works best with
margin: 0 auto;
and a defined width.
- Horizontal centering works best with
- Responsive Design:
- Use relative units like
%
orem
for flexible layouts.
- Use relative units like
Experiment
<!DOCTYPE html> <html lang="en"> <head> <style> .box { width: 200px; height: 100px; background-color: lightblue; margin: 20px auto; } .custom-margin { margin: 10px 30px 50px 70px; background-color: lightgreen; } </style> </head> <body> <div class="box">Box with auto margin</div> <div class="box custom-margin">Box with custom margins</div> </body> </html>