What is the difference between margin, border, and padding in CSS?



As a developer, you may code in multiple languages or on different platforms so, it is ok if you don't remember the syntax, but having a clear concept of the topic is very important. Beginners who are new to coding get confused when it comes to using margin vs padding, and may not know the clear difference between the two.

In this article, we will learn about margin, border and padding.

Margin

Margin is the CSS property which defines the space outside of an element, space between the element border and another element. If the element does not have any border, then the margin will create a space from element content to the next outer element.

When you want to have a different margin for each side of an element, you will have to set the property value individually. The order of setting value for all side goes in clockwise.
CSS has properties which will allow you to set margin for the individual side of the element.

  • Margin-top
  • Margin-right
  • Margin-bottom
  • Margin-left

There is more than one way you can set the value for the margin properties.

  • Auto - the browser will calculate the margin
  • Length - margin in px, cm, pt, etc.
  • % - margin in % of the width of containing element
  • Inherit - inherit the margin from a parent element

Padding

Padding is the CSS property which defines the space between the element content, and it's border. If the element does not have any border, then setting padding value will not have any effect.
Just like margin, you can set the value individually if you want different padding on each side. The order of setting value for all side goes in clockwise.
CSS has properties which will allow you to set the padding for the individual side of the element.

  • Margin-top
  • Margin-right
  • Margin-bottom
  • Margin-left

There is more than one way you can set the value for the padding properties.

  • Length - padding in px, cm, pt, etc..
  • % - padding in % of the width of containing element
  • Inherit - inherit the padding from a parent element

Margin and padding example

margin-padding code

Result

margin-padding code

Border

Border properties will allow you to have a specific style, width and color of an element's border.
Border style: defines the style of the border

  • dotted- Defines a dotted border
  • dash- Defines a dashed border
  • solid- Defines a solid border
  • Many more

Border width: defines the width of the border.

  • The width can be set in px, cm, pt, em, etc. or by using predefined values: thin, medium, thick
  • You can also set the border for the individual side:

Border example


margin-padding code

Result

margin-padding code