Margin and padding in CSS with example

Margins and padding in CSS are very important for creating well-designed layouts. 

Banner

Margins control external spacing between elements, while padding manages internal spacing, collectively shaping the overall visual appeal and structure of webpages.

Let's understand both one by one :

What is margin?


In CSS, margin is the space outside an element's content, creating separation from adjacent elements. 

Margin have 4 sub properties like margin-top, margin-right, margin-bottom, and margin-left. These properties values can be specified in pixels, em units, percentages, or other length units, providing flexibility in defining the spacing around an element.

Consider following example for better understanding 👇

Image 1

Example :

div {
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 15px;
  margin-left: 5px;
}

Shorthand for margin :

div {
  margin: 10px 20px 15px 5px;
}

What is padding?

In CSS, padding refers to the space between an element's content and its inner border. 

Padding have 4 sub properties like padding-top, padding-right, padding-bottom, and padding-left. Padding helps you to control the internal spacing within an element. Padding values can be specified in various units such as pixels, em, percentages, or other length units.

Consider following example for better understanding 👇

Image 2

Example :

div {
  padding-top: 10px;
  padding-right: 20px;
  padding-bottom: 15px;
  padding-left: 5px;
}

Shorthand for margin :

div {
  padding: 10px 20px 15px 5px;
}

When to use margin?

Use margins when you’re adjusting the spacing of an element in relation to another element. For example, a div in relation to another div on the page.

When to use padding? 

Use padding when you’re adjusting the look of an individual element. For example, the amount of pixels between the edge of a div and the text within it.

Thanks for reading this article, if you found this article useful then share it with your friends and share your thoughts in comment section.

Comments