When does padding affect total width, and when doesn’t it?

I’ve been learning CSS on a guess-and-check basis for nearly 1 year and one thing I still haven’t been able to figure out is why adding padding sometimes affects the total width of the element and othertimes doesn’t. Can someone explain this to me in simple terms?


solution

MDN - Box-sizing property

The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements. It is possible to use this property to emulate the behavior of browsers that do not correctly support the CSS box model specification. * * *

By default, padding is not included in an element’s width/height calculation. It’s worth pointing out that the box-sizing property is set to content-box in this case.

MDN - content-box value

This is the default style as specified by the CSS standard. The width and height properties are measured including only the content, but not the padding, border or margin. Note: Padding, border & margin will be outside of the box e.g. IF .box {width: 350px}; THEN you apply {border: 10px solid black;} RESULT {rendered in the browser} .box {width: 370px;} * * *

If the box-sizing property is changed to border-box, the padding is included the element’s width/height calculations, and so is the border.

MDN - border-box value

The width and height properties include the padding and border, but not the margin. This is the box model used by Internet Explorer when the document is in Quirks mode. Note: Padding & border will be inside of the box e.g. IF .box {width: 350px}; THEN you apply {border: 10px solid black;} RESULT {rendered in the browser} .box {width: 350px;}

Further reading:

MDN box model

MDN padding