Wireframe of nested rectangles labeled margin, border, padding & content.

CSS box-sizing

Last Tended

Status: seed

M

etaphor:

Onion

An element in the DOM is like an onion. It has a core & 3 layers. The core is the content (text, image, video, ..). This is wrapped by a padding layer, then a border layer & finally a margin layer. The onion is known as the box-model.

The CSS box-sizing property can be set to:

  • content-box or
  • border-box

content-box [default]

When this value is set & you set the width of an element, you are setting the width of the content box. The core of the onion. The total width of the onion will be this width plus the width of the 3 other layers.

Wireframe of nested rectangles labeled margin, border, padding & content

localhost:3000

* {
   margin: 0;
   padding: 0;
}

div {
   width: 120px;
   padding: 20px;
   border: 4px solid;
   margin: 30px;
}

border-box

When this value is set & you set the width of an element, you are setting the width of the border box. This is made up of the onion core & 2 of the layers. The total width of the onion will be this width plus the width of outer-most layer.

Wireframe of nested rectangles labeled margin, border, padding & content

localhost:3000

* {
   margin: 0;
   padding: 0;
}

div {
   box-sizing: border-box;
   width: 120px;
   padding: 20px;
   border: 4px solid;
   margin: 30px;
}

border-box is more commonly used than content-box. Use the snippet below to set it on all elements.

/index.css

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

Working with Margins

When working with margins, their size can be influenced by things other than the margin value. See consistent / varying gaps.

Where to Next?

A sci-fi robot taxi driver with no lower body
└── CSS
├── 3D
├── Alignment Click Target
Arrow pointing down
YOU ARE HERE
├── Box Sizing
├── Floating Image
├── Layout Component
├── Reset
└── Typography Setup