CSS Box Sizing


🔹 What is box-sizing in CSS?

By default, when you set the width and height of an element in CSS, it only includes the content area — not padding or border.

The box-sizing property allows you to control how the total width and height of an element is calculated.


🔸 Syntax

element {
  box-sizing: content-box | border-box;
}

🔸 Values of box-sizing

1. content-box (Default)
  • Only the content is included in the width and height.

  • Padding and border are added outside the defined size.

.box1 {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  box-sizing: content-box;
}

🟢 Total width = 200 + 202 + 52 = 250px


2. border-box
  • Width and height include padding and border.

  • Actual content area shrinks to accommodate them.

.box2 {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  box-sizing: border-box;
}

🟢 Total width = exactly 200px


🔸 Why Use border-box?

  • Easier to maintain layout sizes

  • More predictable behavior

  • Commonly used in modern web design


🔸 Example: Comparison

<div class="box1">Content Box</div>
<div class="box2">Border Box</div>
.box1, .box2 {
  width: 200px;
  padding: 20px;
  border: 5px solid;
  margin-bottom: 20px;
}

.box1 {
  box-sizing: content-box;
  border-color: red;
}

.box2 {
  box-sizing: border-box;
  border-color: green;
}

🟢 You'll see that .box1 is larger in total width than .box2.


🔸 Apply border-box to All Elements (Best Practice)

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

✅ This ensures consistent sizing across all elements.


Practice Questions

Q1. Set a <div> to use box-sizing: border-box.

Q2. Create two boxes side by side: one with content-box, one with border-box.

Q3. Apply box-sizing: border-box to all elements globally.

Q4. Prevent box from overflowing its parent due to padding.

Q5. Style an input field that remains same width regardless of padding.

Q6. Create a button with fixed width and consistent padding.

Q7. Add 10px padding and 2px border inside a box with box-sizing: border-box.

Q8. Create a responsive card layout using border-box.

Q9. Apply box-sizing using a class .fixed-box.

Q10. Compare two elements’ total widths with different box-sizing values.


Go Back Top