Box Model in CSS

Box Model in CSS

Table of contents

No heading

No headings in the article.

All the HTML Elements can be considered as boxes. The CSS Box Model is defined as a box that wraps around every HTML Element. It consists of a content, padding, border and margin. The figure below represents a box model in CSS.

image.png

The different parts of the box model are as follows:-

  1. content - The area of the box where we can add text, images etc...
  2. padding - It is transparent. It is used to create space around the element's content.
  3. border - It goes around the padding and the content.
  4. margin - It is transparent. It is an invisible space around the box.

The code below demonstrates the box model in CSS.

<style>
        .abc {
            background-color: lightgrey;
            width: 300px;
            border: 15px solid green;
            padding: 50px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="abc">Lorem ipsum dolor sit amet consectetur adipisicing elit. Aspernatur, quo quidem officiis maxime dignissimos sunt, sapiente quos nulla praesentium voluptate dolorum obcaecati placeat quibusdam aliquam aut explicabo atque ea perferendis?
    Vero laboriosam dignissimos nisi rerum debitis deleniti omnis alias, quod ex nemo placeat tenetur. Quam quos aut, iste id temporibus in perferendis impedit aspernatur consectetur quasi nam libero quibusdam! Laborum.
    Ut rerum natus ea! Vero cumque, quam recusandae quas officia commodi quidem ex at esse incidunt quis nisi quaerat impedit nam et laborum! Veniam maiores eum officiis praesentium ipsam sint.
    Cupiditate, saepe quia doloribus deserunt atque porro accusantium voluptas nostrum iure amet asperiores, culpa perferendis fuga dolorum quos vel ratione, blanditiis cumque odit aperiam assumenda veritatis sint commodi autem. Libero!
</div>
</body>

image.png

How the box model works in CSS? To understand the working of box model in CSS, we must have the correct understanding of width and height of an element in a box.

The total width of an element can be calculated as:-

Total width = width + left padding + right padding + left border + right border + left margin + right margin.

The total height of an element can be calculated as:-

Total height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin.

Thank you for reading this short article on Box Model in CSS. Happy Learning !!!