Site icon MoreOnFew

What is the difference between Padding and Margin in CSS ?

CSS3 on MoreOnFew.com

One of the most common confusions that developers starting off with CSS generally have is the difference between Padding and Margin. They are some of the most commonly used CSS properties and I believe it is very important for each one of us to be very clear with the usage of these properties.

Let us take a brief look at both of these properties.

Margin

The CSS property ” margin ” is used to add gaps or spaces around the element. For instance, lets us assume that we have a DIV with id “Div1”. The CSS for the DIV is as follows :

#Div1{
  float:left;
  margin:10px;
  width:100px;
  height:100px;
  border:1px solid black;
}

The DIV would look like the following figure :

Div with margin of 10px

Now if you notice the div, it has moved or has left a gap of 10px on all the sides. All the sides, because if you do not specify the margin for any particular side and just define one single value, the same value is inherited by all the four sides.

The margin property just adds spacing around the element or surrounding the element. Basically in the surrounding area outside the element.

Padding

The “padding” property on the other hand does something similar to what the margin does. But instead of adding the space or gap outside the element, it adds the spacing or gap within the element.  For instance, let’s take the same example we showcased above but now let us add padding value to it. So now our updated CSS would  look like the following :

#Div1{
  float:left;
  padding:10px;
  margin:10px;
  width:100px;
  height:100px;
  border:1px solid black;
}

The Div rendered would look similar to the following figure :

Div with Padding

You can notice that the spacing or gap within the Div has increased by 10px. The gap or spacing between the Div’s border and the text is 10px. That’s because of the 10px padding we have given to it.

The padding property adds spacing or gap within the element. Basically in the area within the div. Padding value also affects the dimensions of the element.

The padding value also adds on to the dimensions of the element while margin property does not do so. For example, the Div1 shown in the figure above has a width and height of 100px respectively. But when we add padding value to it, the width of the element increases by 20px (10 + 10 px) and the height too by 20px (10+10px).

Hope you are now clear with the CSS Padding and Margin properties. Let us know through your valuable comments.

Happy Coding !