The padding property
padding is the inner space between an element's border and its content. The background fills this space too. It is a shorthand for padding-top, padding-right, padding-bottom and padding-left.
Syntax
padding: 16px; /* all four sides */
padding: 16px 24px; /* top and bottom | right and left */
padding: 8px 24px 16px; /* top | right and left | bottom */
padding: 8px 16px 24px 32px; /* top | right | bottom | left */ - Initial value
0- Inherited
- no
- Applies to
- all elements except internal table elements (rows, row groups, columns); table cells (td, th) are fine
Values
| Value | What it does |
|---|---|
<length> | a fixed space: px, rem, em; padding cannot be negative |
<percentage> | a percentage of the containing block's width — even for the top and bottom |
Example
.box {
width: 200px;
padding: 20px;
margin-bottom: 12px;
background: #e0f2fe;
border: 2px solid #0284c7;
}
.border-box {
box-sizing: border-box;
} <div class="box">content-box: 200 + 40 + 4 = 244px</div>
<div class="box border-box">border-box: exactly 200px</div> Result
Good to know
- By default (box-sizing: content-box) padding and border are added to width: a width: 200px block with padding: 20px and a 2px border takes 244px. With box-sizing: border-box they fit into those 200px.
- padding is inside the border, margin is outside. The element's background shows under padding but not under margin.
- On inline elements (span, a) vertical padding is painted but does not push neighbouring lines.
Sources and specification
- MDN: padding — MDN Web Docs
- CSS Box Model Module Level 3 (W3C) — W3C
See also
The margin property
The CSS margin property sets an element's outer spacing: the 1–4 value forms, margin: auto for centering, negative margins and how vertical margins collapse.
The display property
The CSS display property sets how an element takes part in layout: as a block, inline with text, as a flex or grid container, or not at all. Values, examples.
Build a card with CSS
Practice exercise: build a product card in HTML and link an external stylesheet to it.
Card component
A basic card component with a heading, text, and a hover lift effect.
Linking CSS
Lesson 11: three ways to add CSS — an external file via <link rel="stylesheet">, a <style> block in head and the style attribute. Example and task.