Curriculum
Course: CSS Advanced
Login

Curriculum

CSS Advanced

CSS Rounded Corners

0/1

CSS Border Images

0/1

CSS Color Keywords

0/1

CSS Text Effects

0/1

CSS 2D Transforms

0/1

CSS 3D Transforms

0/1

CSS Transitions

0/1

CSS Animations

0/1

CSS Tooltip

0/1

CSS Style Images

0/1

CSS Image Reflection

0/1

CSS Masking

0/1

CSS Buttons

0/1

CSS Multiple Columns

0/1

CSS User Interface

0/1

CSS Box Sizing

0/1

CSS Media Queries

0/1
Text lesson

CSS Box Sizing

The CSS box-sizing property enables the inclusion of padding and border within an element’s overall width and height.

Without the CSS box-sizing Property

By default, an element’s width and height are computed as follows:

width + padding + border = actual width of the element height + padding + border = actual height of the element

Consequently, when you define the width/height of an element, it frequently appears larger than specified, as the element’s border and padding are added to its specified width/height.

The subsequent illustration displays two <div> elements with identical specified width and height:

Image

Image

The two <div> elements depicted above ultimately have differing sizes in the output (due to the padding specified for div2).

Example 

.div1 {
  width: 300px;
  height: 100px;
  border: 1px solid blue;
}

.div2 {
  width: 300px;
  height: 100px;
  padding: 50px;
  border: 1px solid red;
}

The box-sizing property resolves this issue.

With the CSS box-sizing Property

The box-sizing property enables us to incorporate padding and border dimensions into an element’s overall width and height.

When you apply box-sizing: border-box; to an element, its width and height now encompass padding and border dimensions.

ImageImage

Here is the identical example as previously mentioned, with box-sizing: border-box; applied to both <div> elements:

Example 

.div1 {
  width: 300px;
  height: 100px;
  border: 1px solid blue;
  box-sizing: border-box;
}

.div2 {
  width: 300px;
  height: 100px;
  padding: 50px;
  border: 1px solid red;
  box-sizing: border-box;
}

Given the superior outcomes of utilizing box-sizing: border-box;, numerous developers seek to implement this approach for all elements on their web pages.

The following code guarantees that all elements are sized in this more intuitive manner. While many browsers already employ box-sizing: border-box; for numerous form elements (though not all, hence discrepancies in the appearance of inputs and text areas at width: 100%;), extending this to all elements is both prudent and secure.

Example 

{
  box-sizing: border-box;
}