Difference between CSS Padding and Margin with Example

In CSS, margin is the space around an element, outside the element's border. Whereas padding is the space between the border and the content of an element.

For example, consider the following pictorial representation of all the spaces that can be created around an element, to understand where actually the margin and padding lies:

css padding vs margin

The padding is used to create space around the content of an element. Whereas the margin is used create space between specified element and its adjacent element(s). For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p{border: 2px solid maroon;}
      .b{margin: 60px; padding: 14px;}
   </style>
</head>
<body>

   <p class="a">Paragraph without margin and padding.</p>
   <p class="b">Paragraph with margin and padding.</p>
   
</body>
</html>
Output

Paragraph without margin and padding.

Paragraph with margin and padding.

Let me create one more example to differentiate padding and margin in CSS:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{border: 2px solid blue; margin: 80px; padding: 12px;}
   </style>
</head>
<body>
   
   <div>
      This example is created to differentiate padding and margin in CSS
   </div>
   
</body>
</html>
Output
This example is created to differentiate padding and margin in CSS

Margin is the space around an element.

Padding is the space around the content of an element.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!