Skip to main content

CSS Box Model

All HTML elements can be considered as boxes.

The CSS Box Model

In CSS, the term "box model" is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.

The following diagram illustrates how the CSS properties of width, height, padding, border and margin define how much space an attribute will occupy on a web page.

Box model schema

The CSS box model contains the different properties in CSS. These are listed below.

  • Border
  • Margin
  • Padding
  • Content

Let's see in detail.

Border Field

It is a region between the padding-box and the margin. Its proportions are determined by the width and height of the boundary.

Border Field

It is a region between the padding-box and the margin. Its proportions are determined by the width and height of the boundary.

Margin Field

This segment consists of the area between the boundary and the edge of the border.

The proportion of the margin region is equal to the margin-box width and height. It is better to separate the product from its neighbor nodes.

Padding Field

This field requires the padding of the component. In essence, this area is the space around the subject area and inside the border-box. The height and the width of the padding box decide its proportions.

Content Field

Material such as text, photographs, or other digital media is included in this area.

It is constrained by the information edge, and its proportions are dictated by the width and height of the content enclosure.

Width and Height of an Element

In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.

Typically, when you assign the width and height of an attribute using the CSS width and height assets, it means you just positioned the height and width of the subject areas of that component. The additional height and width of the unit box is based on a range of influences.

The specific area that an element box may occupy on a web page is measured as follows:

Size of the boxProperties of CSS
Heightheight + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom
Widthwidth + padding-left + padding-right + border-left + border-right + margin-left + margin-right

Example

div {  
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}

Here is the calculation:

320px (width)

+ 20px (left + right padding)

+ 10px (left + right border)

+ 0px (left + right margin)

= 350px