/

Understanding CSS box-sizing: border-box

Understanding CSS box-sizing: border-box

By default, when you set a width or height on an element, it only applies to the content area. The padding, border, and margin are added on top of this width or height. For example, if you set the following CSS on a <p> element:

1
2
3
4
5
6
p {
width: 100px;
padding: 10px;
border: 10px solid black;
margin: 10px;
}

The browser will render it like this:

Default behavior

However, you can change this behavior by using the box-sizing property. By setting it to border-box, the width and height calculation will include the padding and border. Here’s how it works in the previous example:

1
2
3
4
5
6
7
p {
box-sizing: border-box;
width: 100px;
padding: 10px;
border: 10px solid black;
margin: 10px;
}

The actual size of the element is now 60px because it subtracts the padding and border from the specified width. The margin is still excluded, which is typically considered separate from the element’s box.

This simple property change can have a significant impact on how you calculate the dimensions of your elements. If you find this behavior useful, you can apply it to every element on the page with the following CSS rule:

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

By understanding and utilizing the box-sizing property, you can efficiently control the dimensions of your elements.

Demo on Codepen

Tags: CSS, box-sizing, border-box, dimensions