CSS margin Property

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

Description

The CSS margin property is used to control the spacing around an HTML element. It defines the amount of space between the element's border and adjacent elements or the container it's within. Margins can be set for individual sides (top, right, bottom, left) or as a shorthand property to specify them all at once. Positive values create space, pushing elements apart, while negative values can be used to bring elements closer together. Margins are crucial for achieving proper layout and spacing in web design, helping to create visually appealing and well-organized web pages. Individual properties are: margin-top, margin-right, margin-bottom and margin-left. Negative values are also allowed.

Initial value
See individual properties
Applies to
All elements
Inherited
No
Computed value
See individual properties
Animatable
Yes
JavaScript syntax
object.style.margin

Interactive Demo

Margin Example

Syntax

margin: [ <length> | <percentage> | auto ]{1,4} 

Values

  • <length>Specifies a fixed width. Negative Values are allowed.
  • <percentage>A percentage relative to the width of the containing block. Negative values are allowed.
  • autoauto is replaced by some suitable value, e.g. it can be used for centering of blocks.

    Can have between 1 to 4 values:
    1 value, all 4 sides have the same margin.
    2 values, the top and bottom margins are set to the first value and the right and left margins are set to the second.
    3 values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third.
    4 values, they apply to the top, right, bottom, and left, respectively.

Example

<div class="parent"> 
<div class="child">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
.parent { 
   background: #e2edc1;
   padding: 10px;
} 
.child { 
   border: 3px solid #333391; 
   padding: 10px;
   margin: 20px;
}

Browser Support

The following table will show you the current browser support for the CSS margin property.

Desktop
Edge Chrome Firefox Opera Safari
12113.51
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
18410.1114.4

Last updated by CSSPortal on: 2nd January 2024