DEV Community

Excel Bill
Excel Bill

Posted on

Box-sizing: CSS Box Model Explained

If you're like me, you've probably wondered what box-sizing: border-box and content-box really does and how it works. Well buckle up, cos you're about to get your answers.

One of the fundamental concepts in CSS is the box model, which defines the size and spacing of elements on a web page. The box model consists of content, padding, borders, and margins. Understanding the box model is crucial for creating effective and aesthetically pleasing web designs.

The box-sizing property is a CSS property that gives you control over the size and behavior of an element's box. This property allows you to specify whether the size of an element should include its padding and borders or not.

Everyone who's used CSS knows you just have to set box-sizing to border-box but how does it really work

box-sizing: content-box;

By default, the box-sizing property is set to "content-box," meaning that the size of an element is determined by its content, and padding is added outside of the defined width and height.

css box model || content-box

What this means is that the inner element does not take it's containing element's width into consideration when calculating it's border and padding. By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen.

box-sizing: border-box;

This box-sizing value means that the size of an element is determined by its content, padding, and borders, and they are all included within the defined width and height of the element.

css box model || border-box

This means that the width of an element with the border-box value for box-sizing is the total width of the element, including both its content and padding, plus the width of the borders. In other words, the padding and borders are included within the defined width of the element when using the border-box value for the box-sizing property. This makes it easier to calculate the size of an element and can help you avoid layout issues.

Conclusion

Basically, for content-box, If you set an element's width to 100 pixels, then the element's content box will be 100 pixels wide, and the width of any border or padding will be added to the final rendered width, making the element wider than 100px. *while * for border-box, the browser accounts for any border and padding in the values you specify for an element's width and height. If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width.

consider following me on twitter @Frontend Jedi let's connect!

Top comments (0)