Loading
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 ?

  • 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


PropertyDescription
margin-topSets 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:

Uploaded Image




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

FeatureMarginPadding
DefinitionSpace outside the element's border
Space inside the border, around content
Layout ImpactAffects surrounding elementsAffects the content inside the element
Negative ValuesAllowedNot allowed
Affects BackgroundNoYes (background color extents into padding)
CollapsingVertical margins may collapseNo collapsing
Use CaseSpace between elementsSpace within the element