box-sizing in CSS: How Width and Height Are Calculated
In CSS, a block element is a box (rectangle) made up of four parts: content, padding, border, and margin. box-sizing
determines how total width and height of an element is calculated.
By default (box-sizing: content-box;
), the width
property only sets the width of content, which is very unintuitive. When you set width: 100%
and border
to a element, it becomes wider than the parent element and its border extends beyond the parent element.
|
|
|
|
When we use box-sizing: border-box
on the child element, the width
property sets the width of content, padding and margin, so the child element won’t be wider than the parent element.
It’s recommended to set border-box
to all elements to avoid pitfalls about width and height.
|
|
Further reading:
- The box model - Learn web development | MDN
- box-sizing - CSS: Cascading Style Sheets | MDN
- Inheriting Box-sizing Probably Slightly Better Best-Practice | CSS-Tricks
Image source: the image used in this post is from The box model - Learn web development | MDN#what_is_the_css_box_model.
Comments powered by giscus. If comments are not loaded, giscus may be blocked by your Internet service provider.
Comments powered by Disqus. If comments are not loaded, Disqus may be blocked by your Internet service provider.