For experienced CSS developers this is a very simple topic. But this being a CSS for beginners section of Impressive Webs, I thought it would be good to address this topic as briefly and as effectively as possible for those just starting out.
What Are Margins?
Margins in CSS make up the vertical and horizontal areas between elements. If elements have no margins around them, they will bump right up against each other. Some elements have margins by default, so often even if you haven’t added a margin, you may still see one.
Here’s a visual demonstration of CSS margins:
It’s pretty simple. The space outside of, or between, elements is what comprises the margin areas. This area would also be outside of any borders set on elements.
I should point out there there could be other reasons for elements to have space between them — not just margins. But for the purpose of this simple post, we’ll just assume that all the vertical and horizontal space shown in that image is caused by margin settings.
Margins can be set using the
margin property (which is shorthand, representing the four margin values for an element) or by the longhand
margin-left properties. The order in shorthand is: top, right, bottom, left.
What is Padding?
So what about padding? Well, the padding of an element is the horizontal and vertical space that’s set around the content area of the targeted element. So padding is on the inside of a box, not the outside.
Here’s a visual demonstration of CSS padding:
In this example, there’s a single element with text centered within that element. The centering could be done in a number of ways. We’ll assume it’s done via the CSS padding property. So the padding is the area inside the element that separates the content of the element from the element’s edges. In this example, the element could be a paragraph tag (
Similar to margins, padding is set using the shorthand
padding property, and can also be done using longhand:
So, in brief, margins separate elements from each other and away from page edges, adding space outside of elements. Padding adds space inside of an element, separating the element’s content from the edges of the targeted element.