Course page
Log in

You are watching a free preview. Enroll to open all 26 lessons, track progress and ask the course tutor.

Enroll for $39.99

Section 1: Layout fundamentals

The box model and box-sizing

Article 11 min Lesson 2 of 26 Preview

Every element on the page is a rectangle made of four layers: content, padding, border and margin. How the browser adds those layers together decides how big the element ends up, and this is the source of many "why is this 20 pixels too wide" problems.

By default, CSS uses box-sizing: content-box. That means when you write width: 300px, the 300 pixels apply only to the content. Padding and border are added on top, so an element with 20px padding and a 1px border actually takes 342px. Almost every team switches this behaviour off at the start of a project:

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

With border-box, the width you set includes padding and border. A 300px card stays 300px no matter how much padding you add, which makes layout maths predictable.

Margins behave differently

Padding is inside the element and always adds space. Margins are outside, and vertical margins between block elements in normal flow collapse: if one paragraph has a 24px bottom margin and the next has a 16px top margin, the gap is 24px, not 40px. Margin collapsing does not happen inside Flexbox or Grid containers, which is one reason those layouts feel more predictable.

A good modern habit is to stop using margins for spacing between siblings and use gap on the parent instead. gap works in Flexbox and Grid, never collapses and never adds unwanted space after the last item.

Logical properties

Instead of margin-left and padding-top, you can write margin-inline-start and padding-block-start. These follow the writing direction of the page, so a layout written with logical properties works in right to left languages without extra CSS. Shorthands such as padding-inline: 1rem set both left and right at once.

Try it

Open the starter file 01-box.html, inspect the card in dev tools and look at the box model diagram in the Computed panel. Toggle box-sizing between the two values and watch the total width change. Then replace the margins between cards with gap on the parent.

← → switch lessons