DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question
← From Beginner to Expert in Fundamentals of Frontend
  • The Box Model
  • Specificity & The Cascade
  • CSS Units Deep Dive
  • Stacking Contexts & Z-Index
  • Flexbox Mastery
  • CSS Grid Mastery
  • Centering, Subgrid & Container Queries
  • CSS Custom Properties & Variables
  • Selectors: :has(), Pseudo-classes & Pseudo-elements
  • Responsive Functions: calc(), clamp(), min(), max()
  • Media Queries & Mobile-First Design
  • Transitions & Animations
  • Transforms, Filters & Clipping
  • CSS Methodologies: BEM, CSS-in-JS & Tailwind
  • Typography, Color Spaces & Dark Mode
  • CSS Performance & Optimization
  • CSS Interview Questions — Part 1
  • CSS Interview Questions — Part 2
← From Beginner to Expert in Fundamentals of Frontend

The Box Model

20 min read
Box Modelbox-sizingMargin CollapsingDisplay PropertyContent Box vs Border Box

The Foundation of Every Element on the Web

Every single element in CSS is a rectangular box. Understanding how the browser calculates the size of that box is the single most important CSS concept you will ever learn.

The Four Layers

LayerWhat It IsControlled By
ContentThe actual text, image, or child elementswidth, height
PaddingSpace between content and border (inside the box)padding
BorderThe visible edge of the boxborder
MarginSpace between this box and neighboring boxes (outside)margin

The box-sizing Problem

By default, CSS uses box-sizing: content-box. This means width: 300px only sets the content width. Padding and border are added on top, making the actual rendered width larger than 300px.

The fix that every modern project uses:

*, *::before, *::after {
  box-sizing: border-box;
}

With border-box, the width includes content + padding + border. This is how humans expect sizing to work.

Margin Collapsing

One of CSS's most confusing behaviors: when two vertical margins touch, they collapse into one (the larger value wins).

ScenarioElement A margin-bottomElement B margin-topActual Gap
Both positive30px20px30px (larger wins)
One negative30px-10px20px (sum)
Both negative-30px-20px-30px (more negative wins)

Margins do NOT collapse in Flexbox, Grid, or when an element has overflow: hidden.

The display Property

ValueBehaviorWidthMargin/Padding
blockTakes full width, starts on new line100% of parentAll directions work
inlineFlows with text, no line breakContent onlyHorizontal only
inline-blockFlows inline but respects box modelContent or setAll directions work
noneRemoved from layout entirelyN/AN/A

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.