Tutorial Article
CSS Margin
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. 👉 This adds 20px space on all sides of the paragraph. Attributes Property […]
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.
selector {
margin: value;
}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; |
Example
<!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>Output
Browser Output
The<div>will have space around it (20px on all sides)
The<p>will have extra space above it (30px)
Elements will not touch each other due to margin spacing
Browser Support
Chrome | Firefox | Edge | Safari | Opera | IE9+ |
|---|---|---|---|---|---|
| ✅Yes | ✅Yes | ✅Yes | ✅Yes | ✅Yes | ✅Yes |
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
autofor 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.