How does border-box work?

QuestionsQuestions8 SkillsProCSS Box ModelOct, 18 2025
0123

The border-box value for the box-sizing property changes how the width and height of an element are calculated in CSS. When you set an element's box-sizing to border-box, the following happens:

  1. Includes Padding and Border: The specified width and height of the element include the content, padding, and border. This means that if you set an element to be 100px wide, that 100px will encompass the content area, any padding, and the border.

  2. Simplifies Layout: Using border-box makes it easier to manage layouts because you don't have to add padding and border sizes to the width and height manually. This helps prevent elements from unexpectedly growing larger than intended.

Here’s an example:

.box {
  box-sizing: border-box; /* Includes padding and border in width/height */
  width: 200px;           /* Total width including padding and border */
  height: 100px;          /* Total height including padding and border */
  padding: 20px;         /* Space inside the box */
  border: 5px solid black; /* Border around the box */
}

In this example, the total width of the .box will still be 200px, even with the 20px padding and 5px border. Without border-box, the total width would be 200px + 20px (left padding) + 20px (right padding) + 5px (left border) + 5px (right border), resulting in a total width of 250px.

Using border-box is often recommended for more predictable layouts.

0 Comments

no data
Be the first to share your comment!