CSS Margins

The margin property in CSS is used to create space around elements, outside of any defined borders. The margin property can be set individually for each side or as a shorthand for all sides.

Syntax:

Individual Properties:

  • margin-top: value;
  • margin-right: value;
  • margin-bottom: value;
  • margin-left: value;

Shorthand Property:


margin: [top] [right] [bottom] [left];

Shorthand Values:

1. One Value:


/* All sides will have 10px margin */
p {
    margin: 10px;
}

container1

All sides will have 10px margin

2. Two Values:


/* Vertical (top and bottom) margins are 10px, horizontal (right and left) margins are 20px */
p {
     margin: 10px 20px;
}

container1

Vertical (top and bottom) margins are 10px, horizontal (right and left) margins are 20px

3. Three Values:


/* Top margin is 10px, horizontal (right and left) margins are 20px, bottom margin is 30px */
p {
     margin: 10px 20px 30px;
}

container1

Top margin is 10px, horizontal (right and left) margins are 20px, bottom margin is 30px

4. Four Values:


/* Top margin is 10px, right margin is 20px, bottom margin is 30px, left margin is 40px */
p {
      margin: 10px 20px 30px 40px;
}

container1

Top margin is 10px, right margin is 20px, bottom margin is 30px, left margin is 40px

Auto Margin: You can use margin: auto; to center an element horizontally within its container. This works when the element has a defined width.


/* Horizontally centering a block element */
.centered {
    width: 50%;
    margin: 0 auto;
}

Negative Margins: Negative values are allowed for margins, which can pull elements closer together.


/* Negative margin example */
.negative-margin {
    margin-top: -10px;
}