Use box-sizing: border-box

Practice

The Problem

To make the card the width the challenge asks for, we need to change how the browser measures width. box-sizing sets which part of the box the width we give an element measures. With the default content-box, width measures the content area. Padding and border are added on top of that width.

The box model in Firefox DevTools: content 300 by 150, padding 40, border 5, margin 40
Image: "The box model" by Mozilla Contributors, MDN Web Docs, licensed under CC BY-SA 2.5.

For example, if we give a card width: 320px and padding: 16px, its total width becomes 352px. 16px of padding is added on the left and on the right of the 320px set aside for the content:
16px + 320px + 16px = 352px.

This works when we only want to control the content area, but usually we want to size the whole box (content + padding + border).

The Solution

* {
  box-sizing: border-box;
}

Box-sizing

How does this code work?

* is the universal selector: it matches every element on the page. So this one rule gives every element box-sizing: border-box, and you never have to set it box by box.

The universal selector has the lowest specificity, 0,0,0, so any other selector overrides it. But remember that it still overrides inherited values: it is a selector, even with no specificity, and a rule that matches an element always wins over a value the element would inherit from its parent.

With border-box, on the other hand, width measures the box from the outer edge of one border to the other. Padding and border are included in that width. When width stays fixed and the padding or border grows, the total width of the box stays the same, and the content area shrinks to make room for them.

In the same example, the card's total width is 320px: the 16px of padding on the left and right comes out of that width, leaving 288px for the content area:
320px - 16px - 16px = 288px.

Try it

Lorem ipsum dolor sit amet
paddingcontent areaborder
  1. Use box-sizing: border-box

Join frontendmentor solutions

Join to comment on reads and manage your newsletter subscription.

Sign up free Log in