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.


CSS Margin Quiz

Q1: What does margin affect in CSS?

A. Inside content
B. Border thickness
C. Space outside the element
D. Text alignment

Q2: Which property sets space on the top side of an element?

A. padding-top
B. border-top
C. margin-top
D. top

Q3: Which value centers a block element horizontally?

A. margin: 0 0;
B. margin: auto auto;
C. margin: 0 auto;
D. center: block;

Q4: Which is the correct shorthand for setting all four margins?

A. margin: 10 20 30 40;
B. margin: 10px 20px 30px 40px;
C. margin: 10, 20, 30, 40;
D. margin: top right bottom left;

Q5: What does margin: 10px 20px; set?

A. All sides to 10px
B. Top = 10px, Bottom = 10px, Left & Right = 20px
C. Top = 10px, Right = 20px, Left = 10px, Bottom = 20px
D. Only left and right margins

Q6: What is the default value of margin?

A. 0px
B. 10px
C. auto
D. inherit

Q7: Which margin value can create automatic centering?

A. 0px
B. 50%
C. auto
D. center

Q8: What is the total horizontal margin of this rule: margin: 10px 20px;?

A. 30px
B. 20px
C. 40px
D. 10px

Q9: Which rule removes all margins from an element?

A. margin: none;
B. margin: 0;
C. margin: auto;
D. margin: null;

Q10: What happens if you set a negative margin?

A. It causes an error
B. Nothing changes
C. The element moves in the opposite direction
D. The element disappears

Go Back Top