How to Use Margins in CSS

How to Use Margins in CSS thumbnail
CSS box model

The Cascading Style Sheet (CSS) property called margin will add space to the outside of any element in your HTML document. Margin is part of the CSS box model and creates whitespace around the outside of any padding or border on the element. Here is how to use margins.

Things You'll Need

  • A plain text editor to write the CSS rules
  • A web page you are building
Show More

Instructions

    • 1

      In a CSS stylesheet, each side of an element can have a different margin. When you work that way you set each margin individually. Margin values in the CSS should be given from top, right, bottom and left.

      Here's an example:

      p {
      margin-top: 1em;
      margin-right: 2em;
      margin-bottom: 0.5em;
      margin-left: 2em;
      }

    • 2

      The same rule shown above can be declared using CSS shorthand, like this:

      p {
      margin: 1em 2em 0.5em 2em;
      }

    • 3

      If all the margins are going to be equal, use a rule like this:

      p {
      margin: 1em;
      }

    • 4

      If the top and bottom will be the same and the left and right will be the same, use this shorthand rule:

      p {
      margin: 1em 2em;
      }

      The 1em wlll affect the top and bottom, the 2em will affect the right and left.

Tips & Warnings

  • Margin is transparent, so the background of the element will show through.

Related Searches:

Comments

You May Also Like

Related Ads

Featured