CSS The Box Model box-sizing

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The default box model (content-box) can be counter-intuitive, since the width / height for an element will not represent its actual width or height on screen as soon as you start adding padding and border styles to the element.

The following example demonstrates this potential issue with content-box:

textarea {
    width: 100%;
    padding: 3px;
    box-sizing: content-box; /* default value */
}

Since the padding will be added to the width of the textarea, the resulting element is a textarea that is wider than 100%.

Fortunately, CSS allows us to change the box model with the box-sizing property for an element. There are three different values for the property available:

  • content-box: The common box model - width and height only includes the content, not the padding or border

  • padding-box: Width and height includes the content and the padding, but not the border

  • border-box: Width and height includes the content, the padding as well as the border

enter image description here

To solve the textarea problem above, you could just change the box-sizing property to padding-box or border-box. border-box is most commonly used.

textarea {
    width: 100%;
    padding: 3px;
    box-sizing: border-box;
}

To apply a specific box model to every element on the page, use the following snippet:

html {
    box-sizing: border-box;
}

*, *:before, *:after {
    box-sizing: inherit;
}

In this coding box-sizing:border-box; is not directly applied to *, so you can easily overwrite this property on individual elements.



Got any CSS Question?