164 of 313 menu

The margin property

The margin property sets an element margin. The property value is any size units or the key property auto, which allows the browser to independently calculate the element margin. By default, each browser can add different margins to elements.

The property is shorthand for the margin-top, margin-right, margin-bottom, margin-left properties.

Syntax

selector { margin: value; }

Number of values

The margin property accepts 1, 2, 3, or 4 values, separated by space:

Number Description
1 One value specifies margin on all sides of an element.
2 The first value sets the top and bottom margin, and the second value sets the right and left margin.
3 The first value sets the top margin, the second - right and left, and the third - bottom.
4 The first value sets the top margin, the second - right, the third - bottom, and the fourth - left.

Example

Now we will have a block without margins:

<div id="parent"> <div id="elem"></div> </div> #parent { border: 1px solid black; display: inline-block; } #elem { margin: 0; border: 1px solid red; width: 100px; height: 100px; }

:

Example

Now let’s give the block the margin of 10px:

<div id="parent"> <div id="elem"></div> </div> #parent { border: 1px solid black; display: inline-block; } #elem { margin: 10px; border: 1px solid red; width: 100px; height: 100px; }

:

Example

Let's give the block the margin of 10px on the top and bottom and 20px on the left and right:

<div id="parent"> <div id="elem"></div> </div> #parent { border: 1px solid black; display: inline-block; } #elem { margin: 10px 20px; border: 1px solid red; width: 100px; height: 100px; }

:

Example

Let's give the block the margin of 5px on the top, 15px on the right, 25px on the bottom and 35px on the left:

<div id="parent"> <div id="elem"></div> </div> #parent { border: 1px solid black; display: inline-block; } #elem { margin: 5px 15px 25px 35px; border: 1px solid red; width: 100px; height: 100px; }

:

See also

  • the padding property
    that sets a padding
byenru