CSS3’s Margin Property

Published November 16, 2016 by CSS Newbies.

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

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.

p{
margin-left: 30px;
}

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:

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:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>