What is Box Model in HTML?

What is Box Model in HTML?

  • CSS / HTML
  • 2 mins read

In this tutorial, you will learn what box model in HTML is and how it works.

When a browser represents a web page, it puts each HTML block element in a box. That delivers it easy to control the spacing, borders, and other formatting for elements like headers, sections, headings, and paragraphs. Some inline elements like images are placed in a box as well. To work with boxes, you use the CSS box model.

How does the Box Model Work in HTML?

The below picture shows how the box model works. By default, the box for a block element is as full as the block that holds it and as tall as it requires to be based on its content.

However, you can explicitly define the size of the content section for a block element by using the height and width properties.

CSS Box Model.
The diagram illustrates the CSS box model.

You can see the padding is the space between the content area and a border. Similarly, a margin is the space between the border and the outside of the box.

If you need to calculate the overall height of a box, you can use the formula as described below:

Formula to Calculate the Height of a Box

top margin + top border + top padding + height + bottom padding + bottom border + bottom margin

Formula to Calculate the Width of a Box

left margin + left border + left padding + width + right padding + right border + right margin

When you set the height and width properties for a block element in HTML, you can use any of the CSS units. Mostly we use pixels, so the sizes are fixed.

Notes

  • The CSS box model lets you work with the boxes that a browser places around each block element as well as some inline elements. This enables you to add formattings such as margins, padding, and borders.
  • By default, the box for a block element is wide as the block that contains it and as tall as it needs to be based on its content.

See also