Margins control the space outside an element.
They decide how far one element stays from another.
Let’s learn margins by writing real CSS and seeing how spacing works in layouts.
Here, margin adds space outside the boxes.
Because of margin, the two boxes do not touch each other and look clearly separated.
Margins can be different on each side.
This helps in positioning elements exactly where you want them in a layout.
Real world use of margins
Margins are commonly used to:
- Separate sections
- Space out buttons
- Create clean layouts
- Avoid crowded designs
Without margins, a webpage looks messy and hard to read.
Developer tip
Use margin to control space between elements.
Use padding to control space inside elements.
Mixing them correctly makes your layouts professional.
Practice task
Create two boxes with:
- Border: 2px solid red
- Margin: 30px
- Padding: 15px
Try reducing the margin and notice how close the boxes become.
Next lesson
In the next page, you will learn about the box-sizing property and how it changes the way CSS calculates element size.