What is the difference between Margin, Border, and Padding?

The best way to explain the difference between padding, margin and border is with the CSS box model as you see in the picture. Let's use the CONTENT as an example which it could be a text, an image, etc.

  • The padding is transparent and it's right around the CONTENT. In other words, it controls the space inside an element.
  • The border is the perimeter of the box that goes around the CONTENT and it can have different styles such as different color, size, be dashed or solid, etc.
  • The margin is also transparent and it is outside the border, it provides space in between the CONTENT. In other words, it controls the space outside an element.
  • Padding example image

    Practical Examples

                div { 
                width: 250px;
                border: 18px dashed blue;
                padding: 55px;
                margin: 18px;
                } 
              

    Padding

    Adding the padding to 55px, the padding should expand to allow for 55 pixels of space between the text content and the perimeter of the box. You can also change the padding size of specific sides of the element by using the following properties: padding-right, padding-left, padding-top, padding-bottom.

    Border

    Adding the border to dashed blue 18px wide, the content box should have a border with the values set, as you see in the picture. Like padding, you can also specify the border sides of the element with the properties border-right, border-left, border-top, border-bottom.

    Margin

    Adding the margin to 18px, the margin should expand to allow for 18 pixels around the element. Like padding and border, you can also specify the margin sides of the element with the properties margin-right, margin-left, margin-top, margin-bottom.

    Code example image