The box-sizing property in CSS determines how an element's width and height are calculated, including whether padding and borders are counted within the specified dimensions.
- content-box (default): Width and height apply only to the content area; padding and borders are added outside.
- border-box: Width and height include the content, padding, and border within the specified dimensions.
- Makes element sizing more predictable and simplifies layout design, especially when using border-box.
Syntax
box-sizing: content-box | border-box;content-box
The content-box value for box-sizing calculates an element's width and height, excluding padding and borders, which are added to the specified dimensions.
Syntax:
box-sizing: content-box;Example: Illustrates the use of the box-sizing property whose value is set to content-box.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>box-sizing: content-box</title>
<!--Driver Code Ends-->
<style>
body {
text-align: center;
font-family: Georgia, serif;
}
h2 {
font-size: 28px;
margin-bottom: 50px;
}
.content-box {
width: 200px;
height: 60px;
padding: 20px;
background: green;
color: white;
box-sizing: content-box;
margin: 0 auto;
font-size: 22px;
line-height: 60px;
}
</style>
<!--Driver Code Starts-->
</head>
<body>
<h2>box-sizing: content-box</h2>
<div class="content-box">
GeeksforGeeks
</div>
</body>
</html>
<!--Driver Code Ends-->
border-box
The border-box value for box-sizing calculates an element's width and height, including padding and borders within the specified dimensions, making layout design more straightforward and predictable.
Syntax:
box-sizing: border-box;Example: Illustrates the use of the box-sizing property whose value is set to border-box.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>box-sizing: border-box</title>
<!--Driver Code Ends-->
<style>
body {
text-align: center;
font-family: Georgia, serif;
}
h2 {
font-size: 28px;
margin-bottom: 50px;
}
.border-box {
width: 240px;
height: 100px;
background: green;
color: white;
box-sizing: border-box;
margin: 0 auto;
font-size: 22px;
line-height: 100px;
}
</style>
<!--Driver Code Starts-->
</head>
<body>
<h2>box-sizing: border-box</h2>
<div class="border-box">
GeeksforGeeks
</div>
</body>
</html>
<!--Driver Code Ends-->