CSS Margins

CSS margin attribute defines the space around the element.


margin Clears the surrounding (outer border) element area. The margin has no background color and is completely transparent.

margin You can change the top, bottom, left, and right margins of an element individually, or you can change all attributes at once.

Possible values

value Description
auto Set browser margins.
The result of this will depend on the browser
length Define a fixed margin (using pixels, pt, em, etc.)
% Define a margin using percentages

The following precedent sets distinctive margin for every one of the four sides of a <p> element:


margin-top:100px; margin-bottom:100px; margin-right:50px; margin-left:50px;
Try it yourself »


div.container {
    border: 1px bold blue;
    margin-left: 100px;

p.first {
    margin-left: inherit;
Try it yourself »

Margin - Shorthand Property

In order to shorten the code, it is possible to use all margin attributes specified by margin in one attribute. This is called the shorthand attribute.

The shorthand attribute for all margin attributes is margin :

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left


p {
    margin : 100px 150px 100px 80px;
Try it yourself »

The margin attribute can have one to four values.

  • margin: 25px 50px 75px 100px;
    • Top margin is 25px
    • Right margin is 50px
    • The bottom margin is 75px
    • Left margin is 100px

  • margin: 25px 50px 75px;
    • Top margin is 25px
    • Left and right margins are 50px
    • The bottom margin is 75px

  • margin: 25px 50px;
    • The top and bottom margins are 25px
    • Left and right margins are 50px

  • margin: 25px;
    • All 4 margins are 25px

Use of The auto Value

You can set the margin property to auto to on a level plane focus the component inside its container.

The component will at that point take up the predetermined width, and the rest of the space will be part similarly between the left and right margins:


div {
    width: 250px;
    margin : auto;
    border: 1px bold #a10cb5;
Try it yourself »