0
0
CssConceptBeginner · 3 min read

What is box-sizing in CSS: Explanation and Usage

box-sizing in CSS controls how the total width and height of an element are calculated. It decides whether padding and border are included inside the element's set width and height (border-box) or added outside (content-box).
⚙️

How It Works

Imagine you have a box with a fixed width. Normally, when you add padding or borders, the box gets bigger because these are added outside the content area. This is like wrapping a gift: the box is the gift, and the wrapping paper (padding and border) adds extra size.

The box-sizing property changes this behavior. When set to border-box, the padding and border are included inside the fixed width, so the box size stays the same. It's like having a gift box where the wrapping paper fits perfectly inside the box edges.

This helps keep layouts neat and predictable, especially when designing responsive pages or complex interfaces.

💻

Example

This example shows two boxes with the same width and padding but different box-sizing values. Notice how the total size changes.

css
div {
  width: 150px;
  padding: 20px;
  border: 5px solid black;
  margin-bottom: 10px;
  background-color: lightblue;
}

.box1 {
  box-sizing: content-box;
}

.box2 {
  box-sizing: border-box;
}
Output
<div class="box1">Content-box</div><div class="box2">Border-box</div>
🎯

When to Use

Use box-sizing: border-box when you want to control the total size of elements precisely, including padding and borders. This is very helpful in responsive design, where elements need to fit neatly inside containers without unexpected overflow.

Many developers apply box-sizing: border-box globally to all elements to simplify layout calculations and avoid surprises when adding padding or borders.

Key Points

  • content-box (default): width and height apply to content only; padding and border add outside.
  • border-box: width and height include content, padding, and border.
  • Using border-box makes layout sizing easier and more predictable.
  • Common practice is to set box-sizing: border-box on all elements.

Key Takeaways

The box-sizing property controls if padding and border are inside or outside an element's width and height.
border-box includes padding and border inside the set size, making layouts easier to manage.
content-box is the default and adds padding and border outside the element's size.
Setting box-sizing: border-box globally is a common best practice for consistent layouts.