CSS Margins


In this tutorial, we will learn about CSS Margins. CSS margin property is used to set space around the HTML elements. CSS margin property can be used to set margin separately for each side(top, right, bottom, and left) or together to all four sides.

Setting Margin Individual Sides:

There are four CSS properties to set the margin for each side. These are as follow:

  • margin-top
  • margin-bottom
  • margin-right
  • margin-bottom
p {
  margin-top: 20px;
  margin-bottom: 20px;
  margin-right: 25px;
  margin-left: 25px;
}

In margin properties we can use the following values:

  • auto - the browser automatically calculates the margin for element
  • length - use simple px, pt, cm, values to mention margin.
  • % - specifies a margin in % of the element
  • inherit - it means margin should be inherited from the parent element
p {
  margin-top: 20px;
  margin-bottom: 20px;
  margin-right: auto;
  margin-left: auto;
}

Shorthand Margin Property:

Shorthand margin property used to specify the margin for all four sides in a single line. Please check the following example:

p {
  margin: 15px 20px 30px 25px;
  /* top margin is 15px */
  /* right margin is 20px */
  /* bottom margin is 30px */
  /* left margin is 25px */
}

CSS margin property with three values:

p {
  margin: 15px 20px 25px;
  /* top margin is 15px */
  /* right and left margins are 20px */
  /* bottom margin is 25px */
}

CSS margin property with two values:

p {
  margin: 15px 20px;
  /* top and bottom margins are 15px */
  /* right and left margins are 20px */
}

CSS margin property with a single value:

p {
  margin: 15px;
  /* margin of all four sides is 15px */
}

 



Spread the love:

Please share this page on social media with your friends..

Facebook share Twitter Linkedin share