So you are in the process of learning CSS and you have come across two fundamental CSS properties for keeping space between box elements, CSS margins and CSS padding. They sound like they accomplish the exact same thing so what’s the difference? Are they interchangeable? Should you use one or the other?
At WebAssist we have a large community learning CSS from the ground up. So naturally we get a variety of questions regarding basic CSS properties. In an effort to clarify let’s take a quick look at the difference between the two.
While both CSS properties do offer the ability to add space within a CSS layout there is a definitive separation between the two. To better understand we can use the CSS Box Model and determine the main difference.
As you can see in the above diagram the center is where your element, such as your text, would reside. The space directly around your text element is your CSS padding, followed by the border and then your margin. Therefore, padding defines the spacing between your element and the boarder, while the margin defines the spacing between your border and any other outer elements in your CSS layout.
Here is an example that should help further clarify:
As you can see the margin defines the space outside your border and between other elements, while the padding defines the space between your element and the elements border. Hopefully by understanding the difference you can more effectively utilize your CSS margin and CSS padding properties.
Here’s a pretty cool interactive CSS box model resource which can help even further conceptualize the difference: