CSS Margin Tutorials

The margin is the area outside of the border.

The margin does not have a background, it is transparent. It inherits the background color of the parent element.

Margin properties can be defined using 1 of 3 values: auto (the browser sets the margin), length values (pixels, pt, em, etc.) or percentage (%) values (defined as a percentage of the containing element).

Visual Representation of the Box Model Concept

The image below is a visual representation of the box model concept and shows you where the margin fits into the box model in relation to the element and the border and padding properties.

css box model image

How To Set the Margin using 1 Fixed Value

The CSS rule below shows you how to set the margin of an HTML element using a fixed value.

p { margin:10px; }

How To Set the Margin of all 4 Sides using a Percentage Value

The CSS rule below shows you how to use a percentage value to set the margin of all 4 sides of an HTML element.

p { padding:25%; }

How To Set the Margin of all 4 Sides using 2 Values

The CSS rule below shows you how to set the margin of an HTML element using 2 values in declaration in top/bottom and right/left pair values. The the top and bottom margin in the CSS rule is 25 pixels and right and left is 50 pixels.

p { margin:25px 50px; }

How To Set the Margin of all 4 Sides Using 3 Values

The CSS rule below shows you how to set the margin of an HTML element using 3 values. The first value sets the top margin, the second value sets the right and left margin and the third value sets the bottom value. The top margin in the CSS rule below is 25 pixels, the right and left margin is 100 pixels and the bottom margin is 50 pixels.

p { margin:25px 100px 50px; }

How To Set the Margin of Each Individual Side

The CSS rule below shows you how to set the margin of each side individually.

p { margin-top:25px; margin-right:50px; margin-bottom:75px; margin-left:100px; }