1. css
  2. /properties
  3. /margin



The margin property sets the margin (space) around an element. It specifies the space between the element's border and the adjacent elements in the document flow. The property can accept up to four values, which set the top, right, bottom, and left margins respectively. If fewer than four values are specified, the missing values will be set to the same value as the corresponding opposite margin.


Set a margin of 20 pixels for all sides of a div:

div {
  margin: 20px;

Set different margins for each side of a button:

button {
  margin-top: 10px;
  margin-right: 5px;
  margin-bottom: 20px;
  margin-left: 5px;

Set a margin of 0 for the top and bottom of an image, and 10 pixels for the left and right:

img {
  margin: 0 10px;


<length>Specifies a fixed length for the margin in pixels, ems, rems, etc.
<percentage>Specifies a percentage of the width of the containing element.
autoCenters the element horizontally within the containing element.
inheritInherits the margin from the parent element.
initialSets the margin to its default value.

Best Practices

  • Avoid using negative margin values whenever possible, as they can cause elements to overlap and make the layout difficult to read.
  • Use shorthand properties, such as margin-top, margin-right, margin-bottom, and margin-left, only when you need to set specific values for each side of the element.
  • Don't use margin to create rows in a layout. Instead, use CSS grid or flexbox for this purpose.
  • Use relative units (ems, rems, etc.) instead of pixels for more flexible layouts that adapt to different screen sizes and devices.
  • Consider using a CSS preprocessor like Sass or Less to simplify the process of setting margin values and avoid repetitive code.

Browser Compatibility

ChromeFirefoxSafariInternet ExplorerMicrosoft EdgeOpera