Lecture

Margin

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

Margins do 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 of using the margin property
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 Margins in All Directions

You can set the margins in all directions at once using just the margin property.


Single Value Setting

To set the margin in one direction, just input a single value for the margin property.

Example of single value setting
div { /* Set a 10px margin in all directions */ margin: 10px; }

Vertical and Horizontal Setting

To set vertical and horizontal margins, input two values in the margin property.

Example of vertical and horizontal setting
div { /* Top/bottom margins: 10px, left/right margins: 20px */ margin: 10px 20px; }

Individual Direction Setting

To set margins in all directions individually, input four values into the margin property.

CSS
div { /* Top, right, bottom, left margins: 10px, 20px, 30px, 40px */ margin: 10px 20px 30px 40px; }

Using margin: auto for Centering

margin: auto can be used to center HTML elements horizontally.


Horizontal Centering

To horizontally center a block-level element (like a div), set a width for the element and set the margin property to 0 auto.

CSS
div { width: 100px; /* Set width */ margin: 0 auto; /* Center horizontally */ }

Vertical Centering

Simply using margin: auto will not vertically center an HTML element. To vertically center elements, you will need to use layout techniques such as Flexbox or Grid, which are discussed later.

Mission
0 / 1

What is the most suitable CSS property to fill in the blank?

In CSS, to set the spacing you use the property.
padding
border
margin
width

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

HTML
CSS
Loading...