box-sizing property (border-box & content-box)

 1) 

Suppose if we give width of 200px to our elements and our elements have have some padding and border, by default the width of 200px is applied only on the content and the overall size of the box increases as there is horizontal padding and horizontal border too(vertical padding and vertical border is of no concern to us)

2)

Suppose the padding is 30px on each horizontal side and border is 5 px on each horizontal side. The effective width of the element box will be => 200 + 60 + 10

                                                                                                          =   270px


3) 

if we want the width of 200px from border to border and not only on the content, we use the border- box property of  box-sizing. In Css it is written in the following way:-

box-sizing: border-box;

}

now after giving the border-box value, the entire element box will be 200px irrespective of what value is given to padding and border

by default the value of box-sizing property is content-box.

{

box-sizing: content-box;

}


4) HTML and CSS files:

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

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>

<body>
<div id="my_id">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestias eum eos quae.

</div>

</body>

</html>

CSS file for border-box:

body {

background: green;
margin: 0;
}

#my_id {

width: 200px;

background: brown;

margin: 20px;

border: 5px solid red;

padding: 30px;

box-sizing: border-box;
}

Output:










CSS file for content-box(default even if we don't mention it will be there):

body {

background: green;
margin: 0;
}

#my_id {

width: 200px;

background: brown;

margin: 20px;

border: 5px solid red;

padding: 30px;

box-sizing: content-box;
}

Output:





Comments