CSS Box Sizing

❮ Previous Home Next ❯

What is CSS Box Sizing?

The box-sizing property sets how the total width and height of an element is calculated.

Syntax:

box-sizing: content-box|border-box;

box-sizing: content-box; (default)

The width and height only apply to the content of the element (Resize Browser Window if screen size is less than 380px):

The div element has a width of 300px. But the full width is 300px + 20px (left and right border) + 60px (left and right padding) = 380px!

box-sizing: border-box;

The width and height apply to all parts of the element content, padding and borders:

The full width is 300px.

Example

#example1 {
  box-sizing: content-box;  
  width: 300px;
  height: 100px;
  padding: 30px;  
  border: 10px solid red;
}

#example2 {
  box-sizing: border-box;
  width: 300px;
  height: 100px;
  padding: 30px;  
  border: 10px solid red;
}

Example Explained:

#example1

The CSS box-sizing: content-box; is default value.

width = width + padding-left + padding-right + border-left + border-right

380px = 300px + 30px + 30px + 10px + 10px

height = height + padding-top + padding-bottom + border-top + border-bottom

180px = 100px + 30px + 30px + 10px + 10px

#example1

actual width = width - padding-left + padding-right + border-left + border-right

220px = 300px - 30px + 30px + 10px + 10px

width = actual width + padding-left + padding-right + border-left + border right

300px = 220px - 30px + 30px + 10px + 10px

actual height = height - padding-top + padding-bottom + border-top + border-bottom

20px = 100px - 30px + 30px + 10px + 10px

height = actual height + padding-top + padding-bottom + border-top + border-bottom

100px = 20px - 30px + 30px + 10px + 10px







The following example will set box-sizing: border-box; to all elements using universal selector:

Example

* {
  box-sizing: border-box;
}

h2, p, div {
  width: 300px;
  height: 100px;
  padding: 30px;  
  border: 4px solid red;
}



CSS Box-sizing Property

Property Description
box-sizing Sets how the total width and height of an element is calculated.
❮ Previous Home Next ❯