CSS Box Model (Size, Spacing, Border)

CSS Box Model

width: 200px;  
height: 100px;
padding: 10px;
margin: 20px;
border: 2px solid black;

1. width: 200px;

  • Sets the content width of the element to 200 pixels.
  • It does not include padding, margin, or border.

2. height: 100px;

  • Sets the content height to 100 pixels.
  • Like width, it does not include padding, margin, or border.

3. padding: 10px;

  • Adds space inside the element, between the content and the border.
  • It increases the total size of the element.
  • Example: If width: 200px and padding: 10px, the actual width becomes 220px (200px + 10px left + 10px right).

4. margin: 20px;

  • Adds space outside the element, creating separation from other elements.
  • It does not affect the element’s actual size, only its position.

5. border: 2px solid black;

  • Adds a 2-pixel thick solid black border around the element.
  • The border adds to the element’s total size.

Total Element Size (Box Model Calculation)

By default, the content-box model is used, meaning the total size is calculated as:

Total Width = width + left padding + right padding + left border + right border
Total Height = height + top padding + bottom padding + top border + bottom border

For the given example:

  • Width = 200px + 10px + 10px + 2px + 2px = 224px
  • Height = 100px + 10px + 10px + 2px + 2px = 124px

If box-sizing: border-box; is applied, then width and height include padding and border, keeping the total size fixed.

Example

.box {

    width: 200px;

    height: 100px;

    padding: 10px;

    margin: 20px;

    border: 2px solid black;

    background-color: black;

}

📌 This will create a box with:

black background
200px width and 100px height (content area)
10px padding inside
20px margin outside
2px solid black border

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *