Skip to main content

Padding and Element Width

The CSS width property sets the width of an element's content area. The content area is the part inside the padding, border, and margin (the box model).

So if an element has a set width, any padding is added on top of that width. This is often not what you want.

For example, a <div> with a width of 300px and 25px of padding actually takes up 350px (300 + 25 + 25).

Example

The set width is 300px, but the padding pushes the total width to 350px.

Prompt
An HTML page that shows how padding adds to an element's total width. In an internal <style> block, give a <div> width 300px and padding 25px, plus a border and background. The actual width becomes 350px (300 + 25 + 25). Put text inside.
Output: complete HTML page

Padding and box-sizing

The box-sizing property sets how the width and height of an element are worked out: whether they include the padding and border or not.

It can take these values:

  • content-box — the default. The width and height cover only the content, not the padding or border.
  • border-box — the width and height cover the content, padding, and border.

So to keep the width at 300px no matter the padding, use box-sizing: border-box. The element keeps its total width, and more padding just leaves less room for the content.

Example

With box-sizing: border-box, the total width stays 300px even with padding.

Prompt
An HTML page that uses box-sizing: border-box so padding does not change the total width. In an internal <style> block, give a <div> width 300px, padding 25px, and box-sizing: border-box, plus a border and background. The total width stays 300px. Put text inside.
Output: complete HTML page

All CSS Padding Properties

A summary of the padding properties:

  • padding — sets all the padding in one declaration.
  • padding-bottom — sets the bottom padding.
  • padding-left — sets the left padding.
  • padding-right — sets the right padding.
  • padding-top — sets the top padding.