stackademic

The leading education platform for anyone with an interest in software development.

CSS Box Model

Content, padding, border, margin, and box-sizing behavior

Overview

Every element is a rectangular box with content, padding, border, and margin layers. box-sizing controls whether width/height include padding and border. Understanding the box model prevents layout surprises.

Syntax / Usage

* {
  box-sizing: border-box; /* industry standard reset */
}

.card {
  width: 320px;
  padding: 1rem;
  border: 1px solid #ddd;
  margin: 1rem auto;
}

/* Margin collapse — vertical margins between siblings collapse */
.block { margin-bottom: 1rem; }

/* Inline vs block */
.inline { display: inline; }       /* ignores width/height */
.block { display: block; }         /* full width by default */
.inline-block { display: inline-block; }

Examples

Fixed-size component with border included:

.avatar {
  box-sizing: border-box;
  width: 48px;
  height: 48px;
  border: 2px solid white;
}

Center block with auto margins:

.container {
  max-width: 960px;
  margin-inline: auto;
  padding-inline: 1rem;
}

Common Mistakes

  • content-box default making width: 100% plus padding overflow parent
  • Margin collapse confusing vertical spacing between blocks
  • Padding on inline elements only affects sides, not top/bottom fully
  • Border without box-sizing: border-box breaking grid alignment

See Also

selectors flexbox grid responsive-design