What do Box-sizing in CSS?

Asked 15-Jul-2021
Viewed 559 times

0

What is the use of box-sizing and how many types of box-sizing are available?


1 Answer


1

The CSS box-sizing property is used to form the rules that how the element will capture the height and width.
Let's understand this with a scenario : If you create a div with some height, width, padding and border then that div will capture the size of the window like this-
width + padding + border = actual visible width of an element's box
height + padding + border = actual visible height of an element's box
This means that your div will occupy a width and height greater than its actual width and height
To overcome this problem the boxSizing property is defined.After applying 'box-sizing:border-box' the given width will be as it is without any change.
The syntax of the box-sizing property is as follows:
1.) content-box: the default. Width and height values apply to the element’s content only. The padding and border are added to the outside of the box.
2.) padding-box: The width and height values ​​are applied to the element's content and its padding. The border is attached to the outside of the box. Currently, only Firefox supports the padding-box value.
3.) border-box: Width and height values apply to the content, padding, and border.
4.) inherit: Inherits the box sizing of the parent element.
Let's understand with the help of an example :
<!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title> Mindstick Software Private Limited</title>
    <style>
        .div1 {
            height: 150px;
            width: 400px;
            border: 10px solid red;
            padding: 20px;
        }
        .div2 {
            height: 150px;
            width: 400px;
            border: 10px solid blue;
            padding: 20px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <h1>Box-sizing property</h1>
    <div class='div1'>
        I am the first div with no box-sizing property.
    </div>
    <br />
    <div class='div2'>
        I am the second div with box-sizing property.
    </div>
</body>
</html>
Hope this will clear your confusion.
Happy Coding!