Margin and Padding

The CSS properties, margin and padding, are both aspects of spacing of an element and it’s content. Margin is the outside spacing of an HTML element from other elements. Padding is the spacing of the inside content from the perimeters of the element. Both are very commonly used and each one can be expressed collectively in terms of the sides of an HTML element. However, they can also be used to define the spacing of only one side. Also, both of these properties have a shorthand for defining the spacing of each side.

CSS Margin Property

As mentioned, the margin property gives an invisible border around an element. This property is very useful because it can prevent overcrowding. Time for an example.

Example

width:200px; border-style: solid; border-width:thin; border-color:#000; margin:30px 20px 10px 25px; } </style> <div class=”special”> Sample Text </div>

Result
Sample Text

I have already set the width property and given it a border so that you can better understand this illustration. All right, so what’s with the 4 measurements? The margin property when defined in shorthand is top right bottom left. So, top is 30px, right is 20px, bottom is 10px, and left is 25px.

CSS Padding Property

Example

Result
Sample Text

Now, we see the difference between margin and padding. Obviously, our div was bigger in the padding example. This is because the CSS property padding creates spacing between the div element and its contents. Clearly, this makes the div larger because of the extra internal spacing.

References

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Comment

  1. I have already set the width property and given it a border so that you can better understand this illustration. All right, so what’s with the 4 measurements? The margin property when defined in shorthand is top right bottom left. So, top is 30px, right is 20px, left is 10px, and bottom is 25px.

    You say the margin property when defined shorthand is top right bottom left. But the explanation is top, right, left, bottom. I also found some typo’s I should of told you about. I will as I go along.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.