Background image

Use box-sizing: border-box for simpler element sizing

The CSS property box-sizing defines how the width and height properties behave on a element with border or padding. Normally, when box-sizing has its defualt value of content-box, width and height affect the size of the content. This means that if you have a element with padding: 10px, border: 8px and width: 100px then full width of the element will be 136px. This also affects elements which have a relative width or height.

In this example we have a container element with width: 200px. The child elements width is defined as 100% but it also has a padding of 5em

content
.parent {
width: 200px;
}
.child {
width: 100%;
padding: 10px;
border: 8px;
}

This results in overflowing the container element. Let's now set the child element the property box-sizing: border-box

content
.parent {
width: 200px;
}
.child {
box-sizing: border-box;
width: 100%;
padding: 10px;
border: 8px;
}

Now the width of the child includes the width from padding and border so the child doesn't overflow the parent element anymore.

This makes using width and height much simpler because you don't have to think about how padding and borders affect the size. Some even recommend you set box-sizing: border-box as defaulf for all elements.

* . *{
box-sizing: border-box;
}

Whether you go this far is up to you but it's important to understand how width and height are calculated and how box-sizing affects that.

You might also enjoy