Skip to main content
Practice

Margin

In CSS, margin refers to the outer space of an element. Margin creates space between the element and surrounding elements.

Margin does not affect the actual size of the element.


Setting Individual Margins

margin can be broken down into four sub-properties.

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

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

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

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


Usage 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 */
}

Setting All Margins at Once

The margin property can set the margins for all directions at once.


Usage Example:

  1. Single Direction Setting:
CSS
div {
margin: 10px; /* Sets 10px margin on all sides */
}

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

  1. Individual Side 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 center an HTML element horizontally.


  1. Horizontal Centering: To center a block-level element (e.g., div) horizontally, set a width for the element and set the margin property to 0 auto.
CSS
div {
width: 100px; /* Set the width */
margin: 0 auto; /* Center horizontally */
}

  1. Vertical Centering: margin: auto alone cannot vertically center an HTML element. Vertical centering requires using layout methods such as Flexbox or Grid, which will be explained later.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.