DEV Community

Cover image for Using The CSS3 Box-Sizing Property๐ŸŒˆ๐ŸŒˆ
Macaulay Uzu
Macaulay Uzu

Posted on

Using The CSS3 Box-Sizing Property๐ŸŒˆ๐ŸŒˆ

Box-Sizing

Approximately all HTML elements can be characterized as boxes, ranging from the <a> tag to the <textarea> tag and all of these elements has 5 modifiable dimensions:

  • Width
  • Height
  • Padding
  • Border
  • Margin

The Box-Sizing property was introduced to specify how these dimensions can be calculated and modified to give desired results.
This Box-Sizing property has two values:

  1. Content-Box
  2. Border-Box

Without setting the value, the default value to the Box-Sizing property is content-box

Content-Box

Before CSS3, content-box was known as the W3C Box Model. When the value of Box-Sizing is set to content-box, the addition of the width, height, padding, and border of that element becomes the total size of the element.
i.e
After specifying the width and height on an element, the padding and border of that element are applied subsequently.

Element Width = Left padding + Right padding + Left border + Right border + Width

Element Height = Top padding + Bottom padding + Top border + Bottom border + Height

example:

.box1{
   width: 500px,
   height: 300px,
   border: 10px solid red,
   padding: 30px,
   box-sizing: content-box
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the width of the element is no longer 500 but 580 and the height is no longer 300 but 380.

macaulay1.png

๐Ÿ“Œ the diagram above shows the increase in width and height of the element.


Border-Box

In this box model, a totally different calculation is carried out.
When the width and height of an element is specified, the padding and border are mechanically included in the elements total width and height.
i.e The borders and padding are considered as part of the width and height rather than being an add-on that increases the elements size.

Element Width = Width specified

Element Height = Height specified

example:

.box2{
   width: 500px,
   height: 300px,
   border: 10px solid red,
   padding: 30px,
   box-sizing: border-box
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the the width of the element still remains 500 and the height still remains 300. The padding and border are considered as part of the width and height.

macaulay2.png

๐Ÿ“Œ the diagram above illustrates how the border and padding becomes part of the width and height of the element without increasing the size of the element.


That's It โ•โ•

If you have any feedback, opinion, or comment to the discussion in this article, please let me know in the comment section. I'm always happy for a discussion.

Thanks and See you next time ๐Ÿค๐Ÿค.

Twitter.

Top comments (0)