CSS Margin

CSS Margin

CSS margin Property

The margin property in CSS controls the space outside an element, creating separation between elements in a webpage layout.

1. Syntax

selector { margin: value; /* Applies margin to all sides */ }
  • value → Defines the space (e.g., 10px, 1em, 5%, auto).
  • Common units: pixels (px), percentages (%), em, rem, auto.

2. Margin for Each Side

PropertyDescription
margin-topSets margin at the top.
margin-rightSets margin on the right.
margin-bottomSets margin at the bottom.
margin-leftSets margin on the left.

Example:

div { margin-top: 10px; margin-right: 15px; margin-bottom: 20px; margin-left: 25px; }

✅ Applies different margins to each side.

3. Shorthand Margin (One Line)

SyntaxExplanation
margin: 20px;20px for all sides.
margin: 10px 20px;10px top & bottom, 20px left & right.
margin: 10px 15px 20px;10px top, 15px left & right, 20px bottom.
margin: 5px 10px 15px 20px;5px top, 10px right, 15px bottom, 20px left (clockwise order).

Example:

div { margin: 10px 20px 30px 40px; }

Top → Right → Bottom → Left (Clockwise Order).

4. Auto Margin (Centering an Element)

Using margin: auto; centers a block element horizontally.

div { width: 50%; margin: auto; }

✅ The element stays in the center of the page.

5. Negative Margins

Margins can have negative values to pull elements closer.

div { margin-top: -20px; }

✅ Moves the element 20px closer to the previous element.

6. Margin Collapse (Overlapping Margins)

If two elements have adjacent vertical margins, only the larger margin applies (not the sum).

div { margin-bottom: 20px; } p { margin-top: 30px; }

Effective margin = 30px, not 20px + 30px = 50px.

7. Margin vs Padding (Difference)

PropertyEffect
marginAdds space outside an element (between elements).
paddingAdds space inside an element (between content and border).

Example:

div { margin: 20px; /* Space outside */ padding: 20px; /* Space inside */ }

8. Removing Margin (margin: 0;)

* { margin: 0; }

Removes default margins from all elements.

9. Browser Support

Fully supported in all browsers.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close