CSS Margin


🔹 What is CSS Margin?

CSS Margins are used to create space outside the border of an element.
Margins separate the element from surrounding elements.

You can set margins for:

  • Top

  • Right

  • Bottom

  • Left


🔸 Syntax
element {
  margin: 20px;
}

This sets 20px margin on all four sides.


🔸 Individual Sides

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

🔸 Shorthand Margin Property

margin: 10px 15px 20px 25px;

This means:

  • Top → 10px

  • Right → 15px

  • Bottom → 20px

  • Left → 25px


🔸 Shorter Forms:

margin: 10px 15px;
/* Top & Bottom = 10px, Left & Right = 15px */

margin: 10px 15px 20px;
/* Top = 10px, Left & Right = 15px, Bottom = 20px */

🔸 Auto Margin (Centering)

div {
  width: 300px;
  margin: 0 auto;
}

✅ Horizontally centers a block element inside its parent.


Practice Questions

Q1. Apply a 30px margin to all sides of a <div>.

Q2. Set only the top margin of a <p> to 10px.

Q3. Add 15px margin to the left side of an image.

Q4. Write shorthand margin for: Top = 10px, Right = 20px, Bottom = 30px, Left = 40px.

Q5. Center a block element horizontally using auto margin.

Q6. Set different margins: 10px top, 5px right, 15px bottom, 0 left.

Q7. Add a 25px bottom margin to all <h2> headings.

Q8. Write a rule to apply a 20px right margin to elements with class .sidebar.

Q9. Apply 50px margin only to the left and right of a container.

Q10. Remove all margins from a <body> tag.


Go Back Top