iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Box Sizing

box-sizing controls whether padding and border are inside or outside the width you set. border-box is the sane default.

box-sizing explained

EXAMPLE
/* The legacy default - content-box */
.legacy {
  box-sizing: content-box;        /* DEFAULT - usually painful */
  width: 200px;
  padding: 16px;
  border: 4px solid blue;
  /* total rendered width = 200 + 32 + 8 = 240px */
}

/* The modern default - border-box */
.modern {
  box-sizing: border-box;         /* padding + border inside the width */
  width: 200px;
  padding: 16px;
  border: 4px solid blue;
  /* total rendered width = 200px exactly */
  /* content area = 200 - 32 - 8 = 160px */
}


/* Apply globally - this one line saves you a thousand layout headaches */
*, *::before, *::after {
  box-sizing: border-box;
}


/* Why it matters - a grid example */
.row {
  display: flex;
  width: 400px;
}
.col {
  width: 50%;
  padding: 8px;
  border: 1px solid black;
}

/* With content-box: 50% + 16px + 2px overflows by 36px PER COLUMN */
/* With border-box:  50% INCLUDES the padding and border - they fit */


/* Inherit makes it explicit per-component if you want */
html { box-sizing: border-box; }
*, *::before, *::after { box-sizing: inherit; }


/* You can mix - some elements want content-box for fine control */
.measured-only-content {
  box-sizing: content-box;
}


/* In CSS-in-JS or Tailwind this is set for you globally */
/* Tailwind's preflight does:
 *   *, ::before, ::after { box-sizing: border-box; }
 */

Why it matters

Set `box-sizing: border-box` globally on day one of any project. It matches how designers think about width, fits flexbox and grid naturally, and prevents the most common layout bug in CSS: 50% + padding overflowing the row.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Box Sizing</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Make every element use border-box sizing.

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

Test yourself

Q1. Which value makes width/height include padding and border?
Q2. Which is the historical default?
Q3. Why universal `box-sizing: border-box` helps?

Discussion

Loading…