CSS

Box Sizing


Box sizing is an important CSS property that controls how the width and height of an element are calculated. By default, the width and height of an element are determined only by the content, but box sizing allows you to include padding and border in the total size of the element.

 

Box-Sizing Property

The box-sizing property can take two main values:

  1. content-box (default)
  2. border-box

 

1. Content-Box (Default)

When box-sizing is set to content-box, the width and height of the element only include the content. Padding and border are added outside this box. This is the default behavior in CSS.

 

2. Border-Box

When box-sizing is set to border-box, the width and height of the element include the content, padding, and border. This makes it easier to manage the size of elements, especially when using padding and borders.

 

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Box Sizing Example - Codersmile.com</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="box content-box">
        Content-Box
    </div>
    <div class="box border-box">
        Border-Box
    </div>
</body>
</html>
<style>
* {
    box-sizing: border-box; /* Apply border-box to all elements for easier layout management */
}
body {
    font-family: Arial, sans-serif;
}
.box {
    width: 200px;
    padding: 20px;
    border: 2px solid #000;
    margin: 10px;
    background-color: #f0f0f0;
}
.content-box {
    box-sizing: content-box;
    background-color: #cceeff; /* Different color to distinguish */
}
.border-box {
    box-sizing: border-box;
    background-color: #ffcc99; /* Different color to distinguish */
}
</style>
  • The .content-box element has box-sizing: content-box, so its total width will be 200px (content) + 20px (left padding) + 20px (right padding) + 2px (left border) + 2px (right border) = 244px.
  • The .border-box element has box-sizing: border-box, so its total width will be 200px, including content, padding, and border.

 

Visual Comparison

  • Content-Box: The actual content area is 200px wide, but the total width is 244px because padding and border are added outside the content area.
  • Border-Box: The total width is 200px, including content, padding, and border. The content area is adjusted to fit within this total width.

 

 

Using Box-Sizing in Practice

To simplify layout management, it's common to set box-sizing: border-box globally for all elements. This way, the width and height you set for an element will always include padding and border, making it easier to achieve the desired layout.

/* Apply border-box globally */
*,
*::before,
*::after {
    box-sizing: border-box;
}

By doing this, you ensure a more predictable and consistent layout across your website, including Codersmile.com.