CSS Box Model


The box model is used when talking about design and layout.

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

The box model allows us to add a border around elements, and to define space between elements.

Explanation of the different parts:
ContentThe content of the box, where text and images appear
PaddingClears an area around the content. The padding is transparent
Border border that goes around the padding and content
MarginClears an area outside the border. The margin is transparent

Example

<html>
     <head>
        <style type="text/css">
        .boxmodel {
        width:200px;
        margin:20px;
        padding:30px;
        border:10px solid #ddd;
        background-color:#888;
        color:#fff;
        }
        </style>
        </head>
        <body>
        <div class="boxmodel">BOX MODEL</div>
     </body>
    </html>
Output
BOX MODEL

The total width of an element should be calculated:

  • Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element should be calculated:

  • Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

Share this article on