CSS3’s Margin Property

In CSS, the margin property is used to create space around elements. Without margins, all of our HTML elements would appear pretty right next to each other, with no spacing in between them, which would make for some unattractive designs. To understand how margins work, take a look at the example below:

Screen Shot 2016-11-13 at 10.09.26 AM

Join us in our newest publication:

Without margins, you can see that the text begins exactly next to the border of the div that contains it, which is not exactly ideal in terms of placement. With margins, we can add space between the container and the text by applying a margin-left to the p tag.

  1. p{
  2. margin-left: 30px;
  3. }

Screen Shot 2016-11-13 at 10.09.49 AM

By adding a 30px left margin to the p tag, it creates 30px of space between the p element and the next nearest element(s), which in this case is the container div. Other margin properties you can use are margin-right, margin-top, and margin-bottom, which will add space between the selected element and the next nearest elements int he right, top, and bottom directions, respectively. The values that the margin property takes can be in px, em, rem, or %, in addition to auto and inherit. It’s also important to note that margins usually can’t be applied to inline elements.

If you want to use all 4 margin properties, there’s a helpful shorthand that can be used:

  1. margin: [margin-top] [margin-right] [margin-bottom] [margin-left];

Or if the margin-top and bottom values are the same, and the margin-left and right values are the same, there’s an even shorter shorthand that can be used:

  1. margin: [margin-top & bottom] [margin-right and left];

Share and Enjoy !

0 0