CSS Box Model

This tutorial helps you learn how elements are visually laid out on web pages.

 

What is Box Model?

Each element that can be displayed on a web page comprises of one or more rectangular boxes. The CSS box model typically describes the way rectangular boxes are laid out on a web page. Each box consists of the content area and optional surrounding margin, padding, and border areas, but these boxes can have varying properties and interact with each other differently.

The diagram below illustrates how the width, height, padding, border, and margin CSS properties specify the space an element may take on a web page.

 

The transparent space between the contents of an element and its border (in case it has no border, then the edge of the box) is called padding, whereas the transparent space around the border is called margin.

Moreover, if an element has the background color, it will be visible through its padding area. The margin area always remains transparent; the element's background color does not affect it; however, the margin causes the background color of the parent element to be seen through it.

 

Width and Height of the Elements

When you use the CSS width and height property to set the width and height of an element, you are only setting the width and height of the content area of that element. The element box's actual width and height depend on several factors.

You can calculate the actual space that an element's box might take on a web page as follows:

Box Size CSS Properties
Total Width width + padding-left + padding-right + border-left + border-right + margin-left + margin-right
Total Height height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom

 

Now let's try out the below example for how the box model actually works:

Example :

div {
    width: 300px;
    height: 200px;
    padding: 15px; /* set padding for all four sides */
    border: 10px solid black; /* set border for all four sides */
    margin: 20px auto; /* set top and bottom margin to 20 pixels, and left and right margin to auto */
}

Try With Example

Note: In the CSS box model, an element box's content area is the area where its content, e.g., text, video, image, etc., appears. It may also include descendant elements boxes.