본문으로 건너뛰기

Margin

Margin

In CSS, margin refers to the outer space around an element. It creates space between the element and other elements around it.

Margin does not affect the actual size of the element.


Setting Individual Margins

margin is divided into four sub-properties:

  • margin-top: Sets the top margin of an HTML element

  • margin-right: Sets the right margin of an HTML element

  • margin-bottom: Sets the bottom margin of an HTML element

  • margin-left: Sets the left margin of an HTML element

Example:

CSS
div {
margin-top: 10px; /* Top margin: 10px */
margin-right: 20px; /* Right margin: 20px */
margin-bottom: 10px; /* Bottom margin: 10px */
margin-left: 20px; /* Left margin: 20px */
}


Using Shorthand Properties

You can set margins for all sides at once with the margin property.


Example:

  1. One-direction setting:
CSS
div {
margin: 10px; /* Set 10px margin for all sides */
}

  1. Vertical and Horizontal Setting:
CSS
div {
margin: 10px 20px; /* Top/Bottom margin: 10px, Left/Right margin: 20px */
}

  1. Individual Direction Setting:
CSS
div {
margin: 10px 20px 30px 40px; /* Top, Right, Bottom, Left margins: 10px, 20px, 30px, 40px */
}

margin: auto and Center Alignment

margin: auto is used to place an HTML element in the center of the screen.


  1. Horizontal Center Alignment: To center a block-level element (e.g., div) along the horizontal axis, you specify a width for the element and set the margin property to 0 auto.
CSS
div {
width: 100px; /* Width specified */
margin: 0 auto; /* Center aligned on the horizontal axis */
}

  1. Vertical Center Alignment: You cannot center align an HTML element vertically using margin: auto alone. For vertical center alignment, you need to utilize layout methods like Flexbox or Grid, which will be explained later.