CSS box-sizing property


The box-sizing Property in CSS

The box-sizing property in CSS is used to control how the total width and height of an element are calculated. It determines whether padding and borders are included in the element's total width and height or not. This property helps in managing the layout and design of elements, especially when dealing with complex layouts or responsive designs.

Values of box-sizing

  1. content-box

    • Default Value: This is the default value for the box-sizing property.
    • Calculation: The width and height you set for an element only apply to the content box. Padding and border are added outside of this width and height.
    • Example Calculation:
      • If you set width: 200px, padding: 20px, and border: 5px solid, the total width will be 200px (content) + 20px (left padding) + 20px (right padding) + 5px (left border) + 5px (right border) = 250px.
    .content-box { box-sizing: content-box; width: 200px; padding: 20px; border: 5px solid black; }
  2. border-box

    • Calculation: The width and height you set for an element include the content, padding, and border. This makes it easier to manage the size of elements because the total size remains as specified.
    • Example Calculation:
      • If you set width: 200px, padding: 20px, and border: 5px solid, the total width will be exactly 200px, including the content, padding, and border.
    .border-box { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid black; }

Examples

  1. Using content-box

    <div class="content-box">Content Box</div>
    .content-box { box-sizing: content-box; width: 200px; padding: 20px; border: 5px solid black; background-color: lightblue; }
    • In this case, the total width will be 200px (content) + 20px (padding) + 5px (border) = 250px.
  2. Using border-box

    <div class="border-box">Border Box</div>
    .border-box { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid black; background-color: lightcoral; }
    • Here, the total width will remain 200px, including content, padding, and border.

Use Cases

  • Layout Management: border-box simplifies layout calculations, especially for responsive designs, as it ensures the element’s total size is consistent.
  • Consistent Sizing: Use border-box when you want the padding and border to be included in the element’s specified dimensions, making it easier to maintain consistent sizing.
  • Form Elements: Applying border-box to form elements helps in ensuring their sizes remain predictable, especially when adding padding or borders.