DEV Community

Eddyb Affia
Eddyb Affia

Posted on

The simplest deep dive you'd find on CSS Box Model

When you think of a box what pops up in your mind?
A flat, parallel object with rectangular sides used for a variety of purposes?
Or to put it simply, a rectangular shape with equal sides?

However, it is you perceive a box as, it can be described in a variety of ways, and today, we’d be exploring one of those ways, which is subsequently; A Box Model.

Box Model

Source: GCF GLOBAL

THE CSS BOX MODEL

The term “Box model” is used when referring to designs and layouts.
Think of it like a box that wraps around every HTML element on a webpage or website irrespective of the shape or size of that element.

The box model consists of;

  • Margin: an area outside the border
  • Border: goes around the content and padding
  • Padding: an area around the content
  • The actual content: where texts and images appear

BOX SIZING

The box-sizing property defines how the width and height of an element are calculated. The box-sizing property doesn’t just define how the width and height of an element are being calculated but it also allows us to include the padding and border in an element’s total width and height.

The box-sizing property wouldn’t exist without properties that define them.
Think of these as utilities for controlling how the browser should calculate an element’s total size.
These utilities consist of;

  • Border Box
  • Content Box

Border Box:

box-sizing: border-box
Source: The Garage

This tells the browser to include the element’s borders and padding when you are given a height or width.
The width and height properties include the content, padding, and border, but do not include the margin. Note that padding and border will be inside of the box. For example, .box {width: 350px; border: 10px solid black;} renders a box that is 350px wide, with the area for content being 330px wide.

* {
  box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

Here, the dimensions of the element are calculated as: width = width of the content, and height = height of the content. (Borders and padding are not included in the calculation.)

Content Box:

box-sizing: content-box
Source: The Garage

This tells the browser to add border and padding on top of the element’s specified width and height.
This is the initial and default value as specified by the CSS standard. The width and height properties include the content but do not include the padding, border, or margin. For example, .box {width: 350px; border: 10px solid black;} renders a box that is 370px wide.

* {
  box-sizing: content-box;
}
Enter fullscreen mode Exit fullscreen mode

Here the dimensions of the element are calculated as: width = border + padding + width of the content, and height = border + padding + height of the content.

Top comments (1)

Collapse
 
smahrt profile image
Kubiat Morgan

Nice breakdown, great write-up!