Learn how to build and design websites with our tutorials.

CSS box-sizing Property Tutorial

The CSS box-sizing property with the value border-box places any padding and borders inside the specified width and height area.

For example, this means that if you apply a border of 20 pixels to an element that has a width of 200 pixels and 0 padding, the total width would normally be 240 pixels. This is because of the right and left borders (and 0 padding).

The code example below will output two <div>s, one with a width and height of 200 pixels with a border of 20 pixels and the second <div> with a width and height of 200 pixels with a border of 20 pixels, but it will also have the box-sizing property with the value border-box applied to it.

Also, notice that I have included the -webkit- and -moz- prefixes. Although it should work on all browsers (not including IE7 and below), I still include it since it is still somewhat new.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>

<style>

.normal{
width:			200px;
height:			200px;
margin:			10px;
padding:			0;
border:			40px solid #000;
}
.border-box{
width:			200px;
height:			200px;
margin:			10px;
padding:			0;
border:			40px solid #000;
-webkit-box-sizing:border-box;
-moz-box-sizing:	border-box;
box-sizing:		border-box;

}

</style>

</head>
<body>

<div class="normal">

<p>
This is some text.
</p>

</div>

<div class="border-box">

<p>
This is some more text.
</p>

</div>

</body>
</html>

This is some text.
This is some text.

Notice that the bottom <div> still maintains a total width of 200 pixels.

You might also want to consider applying the box-sizing property with the border-box value to all of your web pages.


*{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}