CSS for Web Development

0% completed

Previous
Next
CSS Margin

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.

Syntax

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:

  • 1 Value: When you specify one value, the same margin is applied on all four sides.
  • 2 Values: The first value sets the top and bottom margins, and the second value sets the left and right margins.
  • 4 Values: Each side has its own margin. The order is top, right, bottom, and left.
  • Individual Properties: You can also set each side's margin separately.
Image

Example 1: 1 Value Shorthand

In this example, we use one value to add the same margin to all sides of a <div> element.

HTML

. . . .

Explanation:

  • Margin: The single value 50px sets a uniform margin on all four sides of the element.

Example 2: 2 Values Shorthand

In this example, we use two values to set different margins for vertical and horizontal spacing.

HTML

. . . .

Explanation:

  • Margin: The first value 20px applies to the top and bottom, while the second value 50px applies to the left and right.

Example 3: 4 Values Shorthand

In this example, we set a different margin for each side using four values.

HTML

. . . .

Explanation:

  • Margin:
    • Top margin is 5px,
    • Right margin is 10px,
    • Bottom margin is 15px,
    • Left margin is 20px.

Example 4: Individual Margin Properties

In this example, we set the margins using individual properties. This allows you to mix and match values if you need more control.

HTML

. . . .

Explanation:

  • Individual Margin Properties:
    • margin-top: Sets a 15px margin above the element.
    • margin-bottom: Sets a 25px margin below the element.
  • Outcome: This method gives you the flexibility to set different margins on specific sides of the element.

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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next