MyInternships.in

CSS Tutorial

CSS Box Model

Every element in CSS is a rectangular box made of four layers: content, padding, border and margin. Understanding this "box model" is essential for layout and spacing.


The four layers of a box

The box model describes how the space around an element is built up in layers, from the inside out.

  1. Content: the actual text, image or other content.
  2. Padding: transparent space inside the border, around the content.
  3. Border: a line that wraps around the padding and content.
  4. Margin: transparent space outside the border, separating this box from others.

Seeing the layers

In the example below, the padding (space inside), border (the line) and margin (space outside) are all visible. Change the numbers and watch the box grow and move.

The box model made visible
Example
<!DOCTYPE html>
<html>
<head>
<style>
  body {
    background-color: #f0f0f0;
    font-family: Arial, sans-serif;
  }
  .box {
    width: 200px;
    background-color: #dbe7ff;
    padding: 20px;                 /* space inside */
    border: 6px solid #2b5cff;     /* the border */
    margin: 30px;                  /* space outside */
  }
</style>
</head>
<body>
  <div class="box">Content sits inside padding, border and margin.</div>
</body>
</html>

How total size is calculated

By default, the width you set applies only to the content. Padding and border are added on top, so the actual space an element takes up is larger than the width value.

Default size math
/* content 200 + padding 20*2 + border 6*2 = 252px total width */
.box {
  width: 200px;
  padding: 20px;
  border: 6px solid #2b5cff;
}

The box-sizing fix

This math surprises many beginners. Setting box-sizing: border-box changes the rule so that width includes padding and border. Now width: 200px means the box is exactly 200px wide, no matter the padding. Many developers apply this to every element.

Make width predictable everywhere
* {
  box-sizing: border-box;
}

Box model reference

LayerSpace typeColored?
ContentText and imagesYes (element color)
PaddingInside the borderYes (element color)
BorderThe wrapping lineYes (border color)
MarginOutside the borderNo (transparent)
💡

Adding box-sizing: border-box to the universal selector (*) at the top of your CSS makes element sizes far easier to reason about. Most modern projects do this.

Key points

  • Every element is a box: content, padding, border, margin.
  • Padding is inside the border; margin is outside it.
  • By default width covers only the content area.
  • Padding and border add to the default total size.
  • box-sizing: border-box makes width include padding and border.

Related CSS Topics

Keep learning with these closely related tutorials.

Ready to use your CSS skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships