Premium CSS Course

CSS Box Model

The CSS Box Model is a fundamental concept in web design that describes how the elements on a web page are structured. Every element on a webpage is considered a box, consisting of four areas: content, padding, border, and margin.

Parts of the CSS Box Model

The CSS Box Model consists of four components:

Visualizing the Box Model

Consider the following diagram, which visually represents the Box Model:


    +-------------------------------+
    |        Margin (Outside)        |
    |  +-------------------------+  |
    |  |       Border (Outside)   |  |
    |  |  +-------------------+  |  |
    |  |  |   Padding (Inside)  |  |  |
    |  |  |  +-------------+    |  |  |
    |  |  |  | Content      |    |  |  |
    |  |  |  +-------------+    |  |  |
    |  |  +-------------------+  |  |
    |  +-------------------------+  |
    +-------------------------------+
    

How the Box Model Affects Layout

The width and height of an element are based on the content area. However, padding, borders, and margins also affect how the element is displayed.

Content Width and Height

By default, the width and height of an element apply only to the content area. This means that padding, border, and margin are not included in the specified width and height. If you set a width of 200px on a div element, the actual space occupied by the element on the page will be larger once you account for padding, borders, and margins.

Box Sizing

To control how the width and height are calculated, you can use the box-sizing property:

Example of box-sizing in use:


        div {
            width: 300px;
            height: 150px;
            padding: 20px;
            border: 5px solid black;
            box-sizing: border-box;
        }
    

In this example, the element's width and height will be 300px and 150px, including padding and borders, due to the border-box value.

Example of the Box Model

Below is an example demonstrating the CSS Box Model in action:


        div {
            width: 200px;
            height: 100px;
            margin: 10px;
            padding: 20px;
            border: 5px solid black;
        }
    

In this case, the element will have:

The total width and height will exceed 200px and 100px due to the padding, border, and margin, unless the box-sizing property is set to border-box.

Best Practices for Using the Box Model