0% completed
CSS margin creates space outside an element's border. It helps control the layout by spacing elements apart. You can use margin as a shorthand property with different values or use individual margin properties.
Follow the code block below to set margins in CSS code.
/* Shorthand syntax for margins with 1, 2, or 4 values */ margin: 20px; /* 1 value: applies 20px on all four sides */ margin: 10px 20px; /* 2 values: 10px for top and bottom, 20px for left and right */ margin: 5px 10px 15px 20px; /* 4 values: top, right, bottom, left respectively */ /* Individual margin properties */ margin-top: value; margin-right: value; margin-bottom: value; margin-left: value;
Explanation:
In this example, we use one value to add the same margin to all sides of a <div>
element.
Explanation:
50px
sets a uniform margin on all four sides of the element.In this example, we use two values to set different margins for vertical and horizontal spacing.
Explanation:
20px
applies to the top and bottom, while the second value 50px
applies to the left and right.In this example, we set a different margin for each side using four values.
Explanation:
5px
,10px
,15px
,20px
.In this example, we set the margins using individual properties. This allows you to mix and match values if you need more control.
Explanation:
This lesson shows you multiple ways to apply margins. Whether you use the shorthand property for simplicity or individual properties for more control, you can create well-spaced, organized layouts with CSS margins.
.....
.....
.....