CSS Properties
CSS box-sizing Property
Photo Credit to CodeToFun
π Introduction
The box-sizing
property in CSS controls how the total width and height of an element are calculated. By default, the width and height of an element are calculated based on its content, padding, and border.
The box-sizing
property allows you to change this behavior to simplify layout calculations and avoid issues with elements that have padding and borders.
π‘ Syntax
The syntax for the box-sizing
property is simple. It can be applied to any block-level or inline-level element.
element {
box-sizing: value;
}
Here, value specifies how the width and height of the element are calculated.
ποΈ Default Value
The default value of the box-sizing
property is content-box.
π Property Values
Value | Description |
---|---|
content-box | The default value. The width and height include only the content of the element. Padding and border are added to the width and height. |
border-box | The width and height include the content, padding, and border. This means that any padding and border are included in the elementβs total width and height, making it easier to manage layout. |
π Example
In this example, we'll demonstrate how the box-sizing
property affects the width and height of a <div> element with padding and border.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS box-sizing Example</title>
<style>
.box-content {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 5px solid black;
}
.box-border {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid black;
}
</style>
</head>
<body>
<h1>Box-Sizing Property Example</h1>
<div class="box-content">
Content-box: Width is 200px, plus padding and border.
</div>
<div class="box-border">
Border-box: Total width is 200px, including padding and border.
</div>
</body>
</html>
π₯οΈ Browser Compatibility
The box-sizing
property is widely supported across all modern browsers, including Chrome, Firefox, Safari, Edge, and Opera. This makes it a reliable property to use for controlling element sizing and layout.
π Conclusion
The box-sizing
property is a useful tool for controlling how the dimensions of an element are calculated.
By choosing between content-box and border-box, you can simplify your layout calculations and create more predictable and consistent designs. Experiment with both values to see which works best for your specific layout needs and project requirements.
π¨βπ» Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS box-sizing Property), please comment here. I will help you immediately.