CSS Box Model

The CSS Box Model is a fundamental concept in web design and layout that defines how elements on a webpage are structured and how their dimensions are calculated.
It consists of several layers or components that surround an HTML element, creating a "box" around it.

Margin
Border
Padding
Content
The Compents

Category

Description

Content

This is the innermost part of the box, which holds the actual content of the element, such as text, images, or other media.

Padding

The padding is the space between the content and the border of the element.

Border

The border surrounds the padding and content and is a visible line that separates the element from its surroundings.

Margin

The margin is the space outside the border and provides separation between the element and other elements on the page.


Example

.box {
    width: 200px;
    height: 100px;
    background-color: #3498db;
    padding: 20px;
    margin: 10px;
    border: 2px solid #2c3e50;
}
Run

Width and Height of an element

The width and height of an element are affected by all these components.
  1. padding
  2. Border
  3. Margin
  4. Width and Height
The total dimensions of the element, including padding, border, and margin, can be calculated as follows
Total Width = Width + Left Padding + Right Padding + Left Border + Right Border + Left Margin + Right Margin
Total Height = Height + Top Padding + Bottom Padding + Top Border + Bottom Border + Top Margin + Bottom Margin

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    /* Apply some styles to the box */
    .box {
      width: 200px;
      height: 100px;
      background-color: #3498db;
      padding: 20px;
      margin: 10px;
      border: 2px solid #2c3e50;
    }
  </style>
  <title>Box Model Example</title>
</head>
<body>
  <!-- Create a box element with some content -->
  <div class="box">
    <h2>Box Model Example</h2>
    <p>This is a simple example demonstrating the CSS box model.</p>
  </div>
</body>
</html>
Run
By the above example we can caluculate the total width and height taken:
Total Width = 200px + 20px + 20px + 2px + 2px + 10px + 10px = 284px
Total Height = 100px + 20px + 20px + 2px + 2px + 10px + 10px = 184px
Here in padding: 20px it takes each 20px in left, right, top and bottom, Same in border and margins.

Quick Recap - Topics Covered

CSS Box Model
Height and Width of an element

Practice With Examples in Compilers

The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compile or Try on own Now

Example js

Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK