box-sizing: border-box

In CSS, box-sizing: border-box; is a property that defines how the width and height of an element are calculated. It’s a crucial tool for creating predictable and consistent layouts.

How it works

By default (box-sizing: content-box), the width and height of an element apply only to its content box (the area inside the padding). This means that any padding or border added to the element will increase its total width and height.

When you set box-sizing: border-box;, the width and height of an element includes the padding and border, as well as the content. So, the specified width and height will be the total size of the element, regardless of the padding and border.

Why use it?

  • Predictable layouts: It makes it easier to create consistent layouts, as the total size of an element remains constant even when you add padding or borders.
  • Simpler calculations: You don’t need to constantly calculate the total size of an element based on content, padding, and border.
  • Improved responsiveness: It can help create more responsive designs by ensuring elements fit within their containers as expected.

Example

.element {
  box-sizing: border-box;
  width: 200px;
  padding: 10px;
  border: 2px solid black;
}

In this example, the element will have a total width of 200px, including the 10px padding on each side and the 2px border on each side.