CodeBlanks Logo Icon CodeBlanks

Box-sizing

CSS course · Beginner · Lesson 30/82

Learn box calculation with box-sizing: border-box.

What is box-sizing?

By default, width measures only the content area; padding and border are added on top. So width: 200px + padding: 20px + border: 5px makes the real width 250 pixels. This is called the content-box model.

If you set box-sizing: border-box, width includes padding and border. The same example stays 200 pixels total; the content area shrinks. Most developers prefer it because the math is more intuitive.

Applying it to every element

To change the default, box-sizing is usually applied to every element. A common pattern:

*, *::before, *::after {
  box-sizing: border-box;
}

This pattern puts every element, including pseudo-elements, into the border-box model. So when you write width: 100%, padding no longer causes overflow. Components like cards and containers now have consistent sizing math.

Exercise Write the box-sizing pattern

Write the pattern that applies box-sizing: border-box to every element and pseudo-element. Selectors: *, *::before, *::after.

Show example solution
*,
*::before,
*::after {
  box-sizing: border-box;
}

Test yourself

  1. Total width under border-box

    /* width: 200px, padding: 20px, border: 5px, box-sizing: border-box */
    /* total width = ____px */
    Show answer
    /* width: 200px, padding: 20px, border: 5px, box-sizing: border-box */
    /* total width = 200px */
  2. What does box-sizing: border-box change?

    • width now measures the content area; padding and border are added
    • width measures the total including padding and border
    • padding and border are removed from the box
    • margin is also included in width
    Show answer

    width measures the total including padding and border — Correct. With border-box, width is the total including padding and border.

  3. Match the box models

    content-box
    Default box model
    border-box
    padding and border inside width
    width: 200px (content-box)
    Content 200px, total larger
    width: 200px (border-box)
    Total 200px, content smaller

All lessons in Beginner