OnlineCBT Logo OnlineCBT
CSS Tutorial
CSS · LESSON 13

CSS Box Model: Content, Padding, Border, and Margin

By Ratan Updated: 15 Oct 2026

Master the core box model that dictates dimensions, spacing, and element boundaries.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Measure all four layers of a box

A box has a content area, padding around that content, a border around the padding, and margin outside the border. Understanding which layer you change makes spacing predictable. Backgrounds normally paint behind content and padding; margins remain outside the box's painted area.

.card {
  width: 240px;
  padding: 20px;
  border: 2px solid #2563eb;
  margin: 16px;
  background: #eff6ff;
}

With the default content-box sizing, the border-box width is 240+40+4 = 284px. Including both horizontal margins, its horizontal outer extent is 316px in this simple calculation. Margin collapsing can affect vertical relationships, so do not generalize every vertical measurement as a simple sum.

Spacing shorthand

.example {
  padding: 8px 16px 12px 20px;
  margin: 1rem 2rem;
}

Four values follow top, right, bottom, left. Two values mean vertical then horizontal. Logical properties such as padding-inline and margin-block express spacing relative to the writing direction and can support multilingual layouts more naturally.

Separate internal and external spacing

Use padding to keep a card's text away from its own border. Use a parent layout's gap or deliberate margins to separate neighboring cards. Adding many unrelated margins to children often makes a layout harder to maintain than one parent gap rule.

Height and overflow

A fixed height can clip text when users zoom or content grows. Prefer natural height with padding, or min-height when a minimum is required. Overflow is a symptom to investigate, not always a reason to hide content.

Practice with developer tools

  1. Inspect a card's box-model diagram and identify each measurement.
  2. Set padding to zero, then margin to zero, observing different effects.
  3. Compute the border-box width for width 200px, 12px padding and 1px borders. Answer: 226px under content-box.
  4. Add a long paragraph and zoom to 200%; confirm the box grows rather than covering adjacent content.

हिन्दी संकेत: padding अंदर की दूरी है, margin बाहर की। Width की गणना box-sizing पर निर्भर है।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat