In css, all elements are placed in boxes. this is called box model.
Margin refers to the distance between the boxes.
Padding refers to the distance between the content and box edge.
By default, when we set the height and width of the element, the padding is also included. meaning if you have element like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
.div1 { width: 300px; height: 100px; border: 1px solid blue; } .div2 { width: 100px; height: 100px; padding: 100px; border: 1px solid red; } |
the actual size will become 300px by 300px, because additional 100px is added to the content from each side. To prevent this, and set height and width such that padding and border is included, use
1 |
box-sizing: border-box; |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
.div1 { width: 300px; height: 100px; border: 1px solid blue; } .div2 { width: 300px; height: 100px; padding: 50px; border: 1px solid red; box-sizing: border-box; } |
source: https://www.w3schools.com/css/css3_box-sizing.asp
https://stackoverflow.com/questions/2189452/when-to-use-margin-vs-padding-in-css