DEV Community

Abdullah Al Numan
Abdullah Al Numan

Posted on

Explain your understanding of the Box Model and how you would implement different box models.

The CSS Box Model is the pattern used by a browser to render elements in an HTML document to the screen.

Layouts and individual elements are represented as rectangular boxes by the browser's rendering engine. The Box Model is used in the box generation step of the Visual Formatting Model. It defines how different parts of an element -- content, padding, border and margin -- work together to create a box that is painted on a screen.

According to the Box Model, a box is composed of four parts:

  1. The content area defined by content edges in four sides.
  2. A padding area, surrounding the content area and defined by padding edges.
  3. The border area, surrounding the padding area and defined by border edges.
  4. And a margin area that defines the space between neighboring elements.

Each of these areas have width and height, which can be set by their respective property identifiers, such as width, height, padding, margin, and border. As in:

div {
  width: 20rem;
  height: 12rem;
  padding: 1rem;
  margin: 2rem;
}
Enter fullscreen mode Exit fullscreen mode

Understanding the Box Model helps us create layouts with accurate, consistent and predictable behavior. The Box Model is implemented in two formats: the Standard CSS Basic Box Model, and an Alternate Box Model. These formats are set by the box-sizing property of an element.

Standard CSS Basic Box Model
The Standard CSS Basic Box Model is the default model used by an element. It is implemented by box-sizing: content-box.

In this model, the height and width set on an element by height, width, max-height, min-height, max-width and min-width apply only within the content edges. Any padding or border added makes the box larger in actual size.

For a style like this:

.box {
  width: 350px;
  height: 150px;
  margin: 10px;
  padding: 25px;
  border: 5px solid black;
}
Enter fullscreen mode Exit fullscreen mode

the padding and borders makes the actual rendered box larger, as shown below:

standard-css-box-model

The Alternative Box Model
The alternative Box Model is implemented with box-sizing: border-box, which sets the width and height of the element to be extended to the border edges. So, any padding and border added will be contained within the width and height of the element. And hence the area of the content will be shrinked by the padding and border values.

.box {
  box-sizing: border-box;
  width: 350px;
  height: 150px;
  margin: 10px;
  padding: 25px;
  border: 5px solid black;
}
Enter fullscreen mode Exit fullscreen mode

It will look like this:

alternate-css-box-model


References

  1. Introduction to the CSS basic box model
  2. The Box Model
  3. Visual Formatting Model - Box Generation

Top comments (0)