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:
p {
width: 100px;
padding: 10px;
border: 10px solid black;
margin: 10px;
}
The browser will render it like this:
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:
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:
*, *:before, *:after {
box-sizing: border-box;
}
By understanding and utilizing the box-sizing
property, you can efficiently control the dimensions of your elements.
Tags: CSS, box-sizing, border-box, dimensions