📜  css box sizing - CSS (1)

📅  最后修改于: 2023-12-03 15:30:08.063000             🧑  作者: Mango

CSS Box Sizing

CSS box sizing is a property that allows you to specify how an element's total width and height is calculated, taking into account the border box, padding box, or content box.

Syntax

The syntax for the CSS box sizing property is as follows:

/* apply to all elements */
box-sizing: border-box;

/* apply to specific elements */
.element {
  box-sizing: content-box;
}
Values

There are two values for the CSS box sizing property:

  • border-box: The width and height of the element includes the content box, padding box, and border box.
  • content-box: The width and height of the element only includes the content box.
Example

Consider the following HTML and CSS code:

<div class="box-sizing-example"></div>
.box-sizing-example {
  width: 200px;
  height: 200px;
  border: 10px solid black;
  padding: 20px;
  box-sizing: content-box;
}

In this example, the width and height of the element is calculated as follows:

  • Width: 200px (specified in CSS) + 20px (left padding) + 20px (right padding) + 10px (left border) + 10px (right border) = 260px.
  • Height: 200px (specified in CSS) + 20px (top padding) + 20px (bottom padding) + 10px (top border) + 10px (bottom border) = 260px.

However, if we change the box-sizing value to border-box, the width and height of the element would be calculated differently:

.box-sizing-example {
  width: 200px;
  height: 200px;
  border: 10px solid black;
  padding: 20px;
  box-sizing: border-box;
}

In this case, the width and height would be calculated as follows:

  • Width: 200px (specified in CSS) = 200px.
  • Height: 200px (specified in CSS) = 200px.
Conclusion

The CSS box sizing property is an important tool for controlling the size of elements on a webpage. Whether you want to include or exclude the padding and borders from the element's total width and height, the box sizing property gives you the flexibility to specify the behavior you want.