Skip to main content

CSS Box Model

CSS Padding

Written by Updated CSS Padding exercises

Control space between content and borders with shorthand, logical properties, percentages, and box-sizing-aware dimensions.

Padding is the space inside an element, between its content and its border. It is what stops text from touching the edge of a button or a card, and the background color fills it.

The difference in one line: margin pushes other elements away, padding pushes the content inward. Margin is covered in CSS Margin, and the line around the padding in CSS Border.

Syntax

css

selector {
    padding: value;
}

Example

css

p {
    padding: 20px;
}

That puts 20px of space inside the paragraph on every side.

The shorthand

It works exactly like margin: one value for all sides, two for top-bottom and left-right, four going clockwise from the top. padding: 10px 20px gives 10px above and below and 20px left and right, a typical button. Each side can also be set on its own, like padding-left.

Two things to know

  • Padding makes the box bigger. With the default box model, width: 200px plus padding: 20px makes a 240px wide box. Set box-sizing: border-box to keep padding inside the width.
  • Percentages use the width. padding-top: 10% is 10% of the parent's width, not its height. That surprise is used on purpose in old tricks to keep a box's shape.

Padding can never be negative.

Complete CSS Padding Example

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS Padding Example</title>
    <style>
        div {
            background-color: lightblue;
            padding: 20px;
            border: 2px solid black;
        }

        p {
            background-color: yellow;
            padding-left: 30px;
        }
    </style>
</head>
<body>

    <div>This is a div with padding.</div>

    <p>This paragraph has left padding.</p>

</body>
</html>

The div has 20px of padding all round, so the text sits away from its border. The paragraph has extra space only on its left, and the yellow background fills that space too.

Browser Support

Feature
Chrome
Edge
Firefox
Safari
padding11211

Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.

Good to know

  • Want more colored space around text? That is padding. Want more empty space between boxes? That is margin.
  • Padding on inline elements like links adds space left and right, but top and bottom padding overlaps the lines around it instead of pushing them away.
  • Bigger padding on buttons and links makes them easier to tap on phones.

CSS Padding exercises

Padding on every side

Give the box 16px of padding on every side.

The HTML your code works on
<div class="box">Box</div>

Result

Check your answer to see it here.