CSS Padding
What is CSS Padding?
CSS padding creates space inside an element, between its content and its border. Unlike margins, padding is part of the element"s background and affects its clickable area.
Padding Properties:
- padding - Sets all four padding values
- padding-top - Sets the top padding
- padding-right - Sets the right padding
- padding-bottom - Sets the bottom padding
- padding-left - Sets the left padding
Padding in Action
Example Code
/* Padding Properties */ .element { /* Apply padding to all sides */ padding: 20px; /* Vertical | Horizontal */ padding: 20px 10px; /* Top | Right | Bottom | Left (clockwise) */ padding: 10px 20px 30px 40px; /* Individual side padding */ padding-top: 10px; padding-right: 20px; padding-bottom: 30px; padding-left: 40px; /* Percentage values */ padding: 5%; /* Viewport units */ padding: 5vw; } /* Padding with different units */ .mixed { padding: 1em 2rem 3% 4px; } /* Padding in flex/grid containers */ .container { display: flex; padding: 20px; } .item { padding: 10px; }
Padding Syntax Options
Shorthand Notation
The padding property accepts 1-4 values, following the clockwise pattern.
Individual Properties
You can also set each padding side individually for more control.
Padding and Box-Sizing
The box-sizing
property determines how padding affects an element"s total dimensions. Understanding this is crucial for predictable layouts.
content-box (Default)
Width and height only include the content. Padding and border are added to the total size.
border-box
Width and height include content, padding, and border. The content size is calculated by subtracting padding and border.
Pro Tip: Many developers use box-sizing: border-box;
for all elements because it makes sizing more predictable. You can apply it globally with:
Padding vs Margin
When to Use Padding
- To create space inside an element, between content and border
- When you want the background color/image to extend into the space
- To increase the clickable area of buttons or links
- When you need space that"s part of the element itself
When to Use Margin
- To create space between elements
- When you need transparent space outside the element
- To center elements horizontally with auto margins
- When the space should not be part of the element"s background
Practical Padding Examples
Button Styling
Card Component
Card Title
This is an example card component with comfortable padding.