Dofactory.com
Dofactory.com
Earn income with your CSS skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

CSS margin

Margin is the spacing outside an element.

The margin property specifies the element‘s margins.

Example

#

A 40-pixel margin added to all sides of an element.

An element with a 40px margin
<style>
  .margin {
    margin: 40px;
    padding: 10px;
    background: aliceblue;
  }
</style>

<div class="margin">
  An element with a 40px margin
</div>

Using margin

This property is a shorthand property for:

The margin values can be any length value, such as, px, %, em, etc.

Margin values can be positive or negative.

Syntax

margin: length | auto | initial | inherit;

Values

#

Value Description
length Default is 0. Sets a margin using any valid length CSS values. Negative values are allowed.
% Sets margin in percent of the width of the containing element
auto Browser calculates a margin
initial Sets the value to its default value.
inherit Inherits the value from its parent element.

More Examples

Click the buttons to see the different margin values.

margin: 5%
<style>
  .margin-examples {
    background: aliceblue;
    padding: 10px;
    height: 200px;
    max-width: 450px;
    margin: 5%;
  }
</style>

<div class="margin-examples">
  margin: 5%
</div>

Click the buttons to see the different margin values.

margin: 20px 40px 60px 80px
<style>
  .margin-example {
    background: aliceblue;
    padding: 10px;
    max-width: 450px;
    margin: 20px 40px 60px 80px;
  }
</style>

<div class="margin-example">
  margin: 20px 40px 60px 80px
</div>

Code Explanation

Single parameter value: all sides of the element use the specified margin value.

Two parameter values: top and bottom, then left and right margins will be set.

Three parameter values: top, left and right, then bottom side.

Four parameter values: top, right, bottom, and left side respectively.

The auto value equalizes left and right margin, placing element in center.


Did you know?

Did you know?

Using margin versus padding

Both properties add spacing to an element.

The margin property adds spacing inside the element.

The padding property adds spacing outside the element.

The difference affects click regions, backgrounds, and other such behavior and properties.


Browser support

This table shows when margin support started for each browser.

Chrome
1.0 Dec 2008
Firefox
1.0 Nov 2004
IE/Edge
6.0 Aug 2001
Opera
3.5 Nov 1998
Safari
1.0 Jun 2003

You may also like


Last updated on Sep 30, 2023

Earn income with your CSS skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

Guides