CSS Box Model

Every element that can be displayed on a web page is comprised of one or more rectangular boxes. This box model typically describes how these rectangular boxes are laid out on a web page.

These boxes can control with different properties and can interact with each other in different ways, but every box has its own content area and optional surrounding padding, border, and margin areas.

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

This diagram can be found when we click on inspect element in right click menu of any webpage. We need to scroll to the end of CSS to get this box model diagram.

Here, the orange section illustrate margin section, light orange section illustrate border section, green section illustrate padding section and blue section illustrate remaining width and height of the box.

Padding is the transparent space between the element’s content and its border (or edge of the box, if it has no border), whereas margin is the transparent space around the border.

Also, if an element has the background color it will be visible through its padding area. The margin area is always remain transparent, it is not affected by the element’s background color, however, it causes the background color of the parent element to be seen through it.

Width and Height of the Elements

Usually when we set the width and height of an element using the CSS width and height properties, in reality we are only setting the width and height of the content area of that element. The actual width and height of the element’s box depends on the several factors.

The actual space that an element’s box might take on a web page is calculated like this:

Box Size         CSS Properties
Total Widthwidth + padding-left + padding-right + border-left + border-right + margin-left + margin-right
Total Heightheight + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom

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



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 */