CSS Margins

margins

margins are one of the most commonly used properties for spacing-out elements within your web page.

The margin clears an area around an element (outside the border). The margin does not have a background colour, and is completely transparent.

The top, right, bottom, and left margin can be changed independently using separate properties.
A shorthand margin property can also be used, to change all margins at once.

Keep in mind you don't have to set all of these properties, just the one's that will help you layout your content the way you desire.

 

 

In CSS, it is possible to specify different margins for different sides depending on your page layout.

When you create the style rule it would look something like this in your style sheet:

.box {
margin-top:10px;
margin-bottom:20px;
margin-right:10px;
margin-left:20px;
}

Once again setting the declarations within a class means you can use it multiple times on a page

the Margin Values

Below is a description of the different values you can use to set your margins, this makes it a very flexible property.

ValueDescription
auto The browser calculates a margin (centers the content)
length Specifies a margin in px, pt, cm  Default value is 0px
% Specifies a margin in percent of the width of the containing element
inherit Specifies that the margin should be inherited from the parent element

 


the 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":

.box {
margin:10px 20px 10px 30px;
}

Note: Always remember when using the shorthand coding method the margins are set in a clockwise direction which would be:

  • Top
  • Right
  • Bottom
  • Left

 

The margin property can have from one to four values.

    • margin: 10px 20px 15px 20px;
      • top margin is 10px
      • right margin is 20px
      • bottom margin is 15px
      • left margin is 20px

    • margin: 10px 20px 15px;
      • top margin is 25px
      • right and left margins are 20px
      • bottom margin is 15px

    • margin: 15px 20px;
      • top and bottom margins are 15px
      • right and left margins are 20px

  • margin: 20px;
    • all four margins are 20px

 


The Margin Properties

Here is a list of the separate properties you can set for margins:

PropertyDescription
margin A shorthand property for setting the margin properties in one declaration
margin-bottom Sets the bottom margin of an element
margin-left Sets the left margin of an element
margin-right Sets the right margin of an element
margin-top Sets the top margin of an element

Leave your comments

Post comment as a guest

0 / 300 Character restriction
Your text should be in between 10-300 characters
terms and condition.
  • No comments found

Get The Latest Browsers

firefoxLogo

google

News Letter

Sign up for news letter