HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

CSS Box Model

All HTML elements can be considered as 'boxes'. In CSS, the term "Box Model" is used when talking about design and layout. It consists of four distinct levels: Margins, Borders, Padding, and the Content area.


Levels of the Box Model

Imagine your element is a framed picture. Each layer of the box model serves a specific purpose:

  • Content: The actual text or image (the photo).
  • Padding: Space around the content (interior empty space).
  • Border: A line that goes around the padding and content (the frame).
  • Margin: Space outside the border (distance between the frame and other walls).
This is the CONTENT area.

Surrounded by Padding, Border, and Margin.


Calculating Total Box Width

By default, when you set the width of an element, it only applies to the content area. To get the total width of the element, you must add the padding and borders on both sides.

Formula: Total Width = [Width] + [Left Padding] + [Right Padding] + [Left Border] + [Right Border]
div {
    width: 300px;
    padding: 10px;
    border: 5px solid gray;
    margin: 20px;
}

/* Total width = 300 + 10(L) + 10(R) + 5(L) + 5(R) = 330px */

The box-sizing Solution

To keep the total width exactly what you specified, you can use box-sizing: border-box;. This automatically shrinks the content area to accommodate any padding or borders.

* {
    box-sizing: border-box; /* Modern standard */
}

div {
    width: 300px;
    padding: 10px;
    border: 5px solid gray;
}

/* Total width remains 300px */

Tip: Always include box-sizing: border-box; in your universal selector (*) for easy responsive layouts.