padding
Example
.sidebar {
width: 300px;
padding: 20px;
}.sidebar {
box-sizing: border-box;
width: 300px;
padding: 20px;
}With the default 'content-box', padding is added on top of width, so the box grows to 340px, while 'border-box' keeps it at 300px.
Common mistakes
- The element grows wider than set because padding is added to
width. - Vertical padding on an inline
spanoverlaps nearby lines instead of pushing them away.
Key points
- Elements with
widthandpaddingusebox-sizing: border-box. - Side padding uses logical properties like
padding-inlinewhere layouts support right-to-left text. - Fixed aspect ratios use
aspect-ratio, not the oldpadding-toppercentage trick.
Interview questions
What is the order of values in the padding shorthand?
Top, right, bottom, left, clockwise; two values set vertical then horizontal, and three set top, horizontal, bottom.
Can padding be negative?
No. Negative padding values are invalid; use negative margin instead.
What is the difference between padding and margin?
padding is space inside the border and shows the background; margin is space outside the border and is transparent.