CSS Margin

Last Updated Jul 21, 2015, 12:00:06 PM





What is CSS Margin?

The css margin property sets the margin for all four sides(top,bottom, left, right). It is a shorthand to avoid setting each side separately with the other margin properties: margin-top, margin-right, margin-bottom and margin-left.

Negative values are also allowed.

Definition and Usage

Initial Value The concatenation of the initial values of its length properties
  • margin-bottom:0
  • margin-left:0
  • margin-right:0
  • margin-top:0
Applies to all elements. It also applies to ::first-letter and ::first-line.
Inherited no
Percentages refer to the width of the containing block
Media Visual
Computed Value as each of the properties of the shorthand:
  • margin-bottom: % or the absolute length
  • margin-left: % or the absolute length
  • margin-right: % or the absolute length
  • margin-top: % or the absolute length
Animatable Yes, as a length
Canonical Order The unique non-ambiguous order defined by the formal grammer
Syntax

One single value applies to all four sides.

Two values apply first to top and bottom, the second one to left and right.

Three values apply first to top, second to left and right and third to bottom.

Four values apply to top, right, bottom and left in that order (clockwise).

Example
Try It Now

CSS Auto Margin

Try It Now

CSS All Sides Margin

Watch GIF Try It Now

CSS margin with pixels

Try It Now

Top and Bottom Only Margin

Try It Now

Top and Bottom Only Margin

Try It Now

Top, left and right, Bottom Margin

Try It Now

Top, left,right and Bottom Margin

Try It Now

IMPORTANT: To center something horizontally in modern browsers, use display: flex; justify-content: center; . However, in older browsers like IE8-9, these are not available. In order to center an element inside its parent, use margin: 0 auto;

CSS Margin - Shorthand Property

to shorten the code, it is possible to specify all the margin properties in one property. This is called a shorthand property.

The shorthand property for all the margin properties is "margin":


Try It Now

Browser compatibility
Feature
Basic support 1.0 1.0 (1.7 or earlier) 1.0 3.5 3.0 1.0 1.0
auto value 1.0 1.0 (85) 1.0 3.5 6.0(strict mode) ? ?


Property Description Video Live Example
margin-top Sets the margin space on the top Watch GIF Try It Now
margin-bottom Sets the margin space on the bottom Try It Now
margin-left Sets the margin space on the left Watch GIF Try It Now
margin-right Sets the margin space on the right Watch GIF Try It Now

Other Advanced CSS Margin Properties you might want to Learn

CSS margin-left property

CSS margin-right property

CSS margin-top property

CSS margin-bottom property





Sources and Credits

The source of the content has been referred and updated with Mozilla Foundation and W3C Organization

Last Updated Jul 21, 2015, 12:00:06 PM