Lesson 9 – CSS3 Box Sizing

This box-sizing property is used to change the width and height of an element. It works as follow.

Border + width + padding = Rendered or actual width of an element

Border + height + padding = Rendered or actual height of an element

It means the element appear wider and higher than the given size. It happens because the padding and the border add to the width and height of an element, making it look bigger than it is supposed to be.

Have a look at the following example.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS3 Box Sizing</title>
    <style>
        .div1 {
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }
        .div2 {
            width: 200px;
            height: 200px;
            border: 1px solid greenyellow;
            padding: 50px;
        }
    </style>
</head>
<body>
    
Box with adder border
<br>
Box with added border and padding
</body> </html>

Here is how the code will transform into the browser.

As you can see, the div2 looks larger than div1 despite having the same width and height. This is because of the padding which added to the width and height of div2.

The box-sizing property provides easy solution to this problem. We will explain it with the help of the following example.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS3 Box Sizing</title>
    <style>
        .div1 {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            box-sizing: border-box;
        }

        .div2 {
            width: 200px;
            height: 200px;
            border: 1px solid greenyellow;
            padding: 50px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    
Box with added border
<br>
Box with added border and padding
</body> </html>

The above code will produce the following results.

Now you can see that both elements have the same width and height because of the box-sizing property despite having added padding and border. Therefore, box-sizing is an extremely important property to use. It can greatly help you overcome problems related to box size, height, and width.

In the next lecture, we will learn more about measurement units in CSS3.