- Home
- /
- Tutorials
- /
- CSS Tutorial
- /
- CSS Margin
CSS Box Model
CSS Margin
Control space outside an element's border, use logical margins, understand vertical margin collapsing, and center constrained blocks safely.
The CSS Margin property is used to create space outside an element’s border.
It controls the distance between an element and surrounding elements, helping to create proper layout and spacing on a webpage.
Margins are transparent and do not have a background color.
Syntax
css
selector {
margin: value;
}Example
css
p {
margin: 20px;
}👉 This adds 20px space on all sides of the paragraph.
Attributes
| Property | Description | Example |
|---|---|---|
| margin | Sets margin on all sides | margin: 10px; |
| margin-top | Sets top margin | margin-top: 20px; |
| margin-right | Sets right margin | margin-right: 15px; |
| margin-bottom | Sets bottom margin | margin-bottom: 25px; |
| margin-left | Sets left margin | margin-left: 10px; |
Margin behavior in real layouts
Vertical margins between blocks can collapse into a single margin instead of being added together. Flex and Grid items do not collapse their margins, which is one reason spacing can change when a container switches layout modes. Prefer margin-inline and margin-block when the spacing follows writing direction, and use auto only when the layout algorithm has free space to distribute. The supporting concepts are explained in CSS Padding and Box Sizing.
Example
Complete CSS Margin Example
html
<!DOCTYPE html>
<html>
<head>
<title>CSS Margin Example</title>
<style>
div {
background-color: lightblue;
margin: 20px;
padding: 10px;
}
p {
background-color: yellow;
margin-top: 30px;
}
</style>
</head>
<body>
<div>This is a div with margin.</div>
<p>This paragraph has top margin.</p>
</body>
</html>Browser Support
Feature | Chrome | Edge | Firefox | Safari |
|---|---|---|---|---|
| margin | 1 | 12 | 1 | 1 |
Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.
Notes
- Margin creates space outside the element
- It is different from padding (which is inside spacing)
- You can set margin for individual sides Supports shorthand values: margin: 10px 20px; (top-bottom, left-right)margin: 10px 15px 20px 25px; (top, right, bottom, left)
- Margin can be set to auto for centering elements
Conclusion
CSS Margin is essential for controlling layout spacing between elements. It helps create clean, organized designs by ensuring proper distance and alignment across different parts of a webpage.
