DEV Community

ABISHEK M
ABISHEK M

Posted on

Box Sizing in CSS

When creating a webpage using CSS, we use properties like width, height, padding, and border to control the size of an element. Sometimes, the final size of an element can become bigger than the width or height we give. This happens because of the way CSS calculates the size of an element. The box-sizing property helps us control this behavior.

What is Box Sizing?

box-sizing is a CSS property that tells the browser how to calculate the total width and height of an element.

There are two common values of box-sizing:

  • content-box
  • border-box

1. Content Box

content-box is the default value of the box-sizing property.

When we use content-box, the width only applies to the content. The padding and border are added separately.

.box {
    width: 200px;
    padding: 20px;
    border: 5px solid black;
    box-sizing: content-box;
}
Enter fullscreen mode Exit fullscreen mode

Here, the content width is 200px. The left and right padding add 40px, and the borders add another 10px.

So the total width becomes:

200px + 40px + 10px = 250px

This can sometimes make the element bigger than we expected.

2. Border Box

border-box works differently. When we use border-box, the given width includes the content, padding, and border.

.box {
    width: 200px;
    padding: 20px;
    border: 5px solid black;
    box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

Here, the total width will remain 200px.

The browser automatically adjusts the content size to make space for the padding and border.

This makes it easier to control the size of elements.

Why is Border Box Useful?

border-box is commonly used in modern websites because it makes sizing easier and more predictable.

For example, we can apply it to all elements using:

* {
    box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

Now, the width and height we give to elements will include their padding and borders.

Conclusion

The box-sizing property is useful for controlling how the size of an HTML element is calculated. The default value is content-box, where padding and border are added outside the given width and height. With border-box, the width and height include the content, padding, and border.

For beginners, using border-box can make CSS layouts easier to understand and prevent unexpected changes in element sizes.

Top comments (0)