border-box vs content-box
Written byPhuoc Nguyen
Created
03 Sep, 2020
Category
CSS
`border-box`
and `content-box`
are two values of the `box-sizing`
property.
Unlike the `content-box`
, the `border-box`
value indicates that the dimension of an element will also include the border and padding.Let's assume that we have a div element whose size is
`200px x 100px`
, the border and padding are `5px`
and `10px`
respectively.css
.div {
width: 200px;
border: 5px;
padding: 10px;
}
In the content box model, the content inside of element will have the same dimension as the element.
css
.div {
/* ... */
box-sizing: content-box;
}
shell
// Content box
◀︎──── 200px ────▶︎
┌───────────────────────────────────────────────────────┐
| |
| ┌───────────────────────────────────────┐ |
| | | |
| | ┌───────────────┐ | |
| Border| Padding | Content | | |
| | | | | |
| 5px | 10px | 200px | 10px | 5px |
|◀︎─────▶︎|◀︎─────────▶︎|◀︎─────────────▶︎|◀︎─────────▶︎|◀︎─────▶︎|
| | | | | |
| | └───────────────┘ | |
| | | |
| └───────────────────────────────────────┘ |
| |
└───────────────────────────────────────────────────────┘
In the border box model, the content's dimension has to subtract the border and padding from the element's dimension.
Specifically, the content's width is
`200 - 5 * 2 - 10 * 2 = 170px`
.shell
// Border box
◀︎──────────────────────── 200px ────────────────────────▶︎
┌───────────────────────────────────────────────────────┐
| |
| ┌───────────────────────────────────────┐ |
| | | |
| | ┌───────────────┐ | |
| Border| Padding | Content | | |
| | | | | |
| 5px | 10px | 170px | 10px | 5px |
|◀︎─────▶︎|◀︎─────────▶︎|◀︎─────────────▶︎|◀︎─────────▶︎|◀︎─────▶︎|
| | | | | |
| | └───────────────┘ | |
| | | |
| └───────────────────────────────────────┘ |
| |
└───────────────────────────────────────────────────────┘
#See also
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn