Home 〉 CSS Tutorials 〉 CSS 'box-sizing' Property Explained with Simple Examples for Beginners
CSS 'box-sizing' Property Explained with Simple Examples for Beginners !
Confused about how padding and borders affect element dimensions? The CSS `box-sizing` property determines how the total width and height of an element are calculated. This tutorial clarifies the difference between `content-box` and `border-box` models. By understanding `box-sizing`, you can create layouts that behave predictably across browsers. Gain control over your element sizing with this property. Read the detailed tutorial on CSS 'box-sizing' Property
When designing web layouts, the 'box-sizing' property helps you control how element sizes are calculated. It can prevent layout issues and save you from unexpected element overflows.
Let's break it down and understand how 'box-sizing' works step by step.
In CSS, every element is a box. The size of that box can be calculated in two ways:
Syntax ✍
selector {
box-sizing: border-box | content-box;
}
Let's see the difference with examples.
<!DOCTYPE html>
<html>
<head>
<style>
.content-box {
width: 200px;
padding: 20px;
border: 5px solid blue;
box-sizing: content-box;
}
</style>
</head>
<body>
<div class="content-box">This box uses content-box</div>
</body>
</html>
output 📌
You can Try the above code by changing the values in our user-friendly code editor by clicking the "Try It" button and see the output of the same.
Meaning: Total width = 200 (content) + 40 (padding) + 10 (border) = 250px
<!DOCTYPE html>
<html>
<head>
<style>
.border-box {
width: 200px;
padding: 20px;
border: 5px solid green;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="border-box">This box uses border-box</div>
</body>
</html>
output 📌
You can Try the above code by changing the values in our user-friendly code editor by clicking the "Try It" button and see the output of the same.
Meaning: Total width = 200px
Many developers reset box-sizing for all elements to 'border-box' using this global rule:
Example 📄
* {
box-sizing: border-box;
}
The 'box-sizing' property is simple but powerful. It gives you more control over your element sizes, especially when building responsive layouts. Use 'border-box' for easier and consistent designs.
By understanding how boxes are sized, you'll avoid unexpected spacing and layout issues.
The default value is 'content-box'.
'border-box' is preferred in most modern layouts as it's easier to manage spacing.
Yes. Use '* { box-sizing: border-box; }' to apply it globally.
No. It only affects how width and height are calculated inside the box (content, padding, border).
Yes, using 'border-box' makes responsive layouts more consistent and easier to maintain.