Margins
In CSS, margins are used to create space outside the borders of an element. They help you control spacing between elements and the browser window, making your layout clean and organized.
What Are Margins ?
Syntax:
Margin Properties
Syntax:
Example:
Example: Margin Using Pixels
Output:
.webp)
Margins with Percentages
You can use percentage values to make layouts more responsive.
Margins adjust based on the width of the parent container.
Margins on Inline Elements
You can apply margins to inline elements like <strong>, but top and bottom margins have no visible effect.
Example:
Only the left and right margins will apply in most browsers.
Difference Between Margin and Padding
- Margins define the outer space of an HTML element.
- They are completely transparent and do not affect background color.
- They help in separating elements visually on the page.
Syntax:
selector { margin: value;}
- You can use values in pixels (px), centimeters (cm), percentages (%), or even auto.
- Negative values are allowed in margins.
Margin Properties
Property | Description |
---|---|
margin-top | Sets the top margin of an element |
margin-right | Sets the right margin of an element |
margin-bottom | Sets the bottom margin of an element |
margin-left | Sets the left margin of an element |
Syntax:
margin: top right bottom left;
Example:
margin: 50px 100px 150px 200px;
This will result in:
- Top: 50px
- Right: 100px
- Bottom: 150px
- Left: 200px
Example: Margin Using Pixels
<!DOCTYPE html><html><head> <style> p { background-color: pink; } .ex { margin: 50px 100px 150px 200px; } </style></head><body> <p>This paragraph has no margin.</p> <p class="ex">This paragraph has specific margin values on all sides.</p></body></html>
Output:
.webp)
Margins with Percentages
You can use percentage values to make layouts more responsive.
<h1 style="margin: 5%; background-color: #eee;">Heading with 5% margin</h1>
Margins adjust based on the width of the parent container.
Margins on Inline Elements
You can apply margins to inline elements like <strong>, but top and bottom margins have no visible effect.
Example:
<strong style="margin-top: 25px; margin-left: 25px; background-color: #eee;"> Quipoin</strong>
Only the left and right margins will apply in most browsers.
Difference Between Margin and Padding
Feature | Margin | Padding |
---|---|---|
Definition | Space outside the element's border | Space inside the border, around content |
Layout Impact | Affects surrounding elements | Affects the content inside the element |
Negative Values | Allowed | Not allowed |
Affects Background | No | Yes (background color extents into padding) |
Collapsing | Vertical margins may collapse | No collapsing |
Use Case | Space between elements | Space within the element |