Logo hdtoledo
hdtoledo.dev
Módulos_del_Sistema
MÓDULO_TEÓRICO

The Secret of the CSS Box Model

The Box Model

Everything on the Web is a Box

In CSS, every rendered element on the screen (a button, heading, image, or card) is conceptually a rectangular box.

Understanding how box dimensions are calculated is the secret to never again struggling with overflowing elements or broken layouts.


1. The 4 Layers of the Box Model

From the inside out:

  1. Content: The actual text, icon, or image (width and height).
  2. Padding (Inner spacing): The breathing room between content and border.
  3. Border: The dividing frame around the padding.
  4. Margin (Outer spacing): The invisible forcefield pushing neighboring boxes away.

2. The Lifesaver: box-sizing: border-box

In traditional CSS (content-box), if you set width: 200px, padding: 20px, and border: 2px, the actual rendered width was 244px (200 + 20 + 20 + 2 + 2), constantly breaking grids.

With box-sizing: border-box, the total width is strictly preserved:

css
.login-card { width: 380px; /* TOTAL width will remain exactly 380px */ padding: 32px; /* Content scales inside */ border: 1px solid rgba(0, 240, 255, 0.2); margin: 20px auto; /* Centers the box horizontally */ background: #121420; border-radius: 12px; }

3. Display Types

  • display: block: Takes 100% available width and breaks into a new line (<div>, <p>, <h1>, <form>).
  • display: inline: Only takes content width and ignores width / height (<span>, <a>, <strong>).
  • display: inline-block: Stays on the same line like inline, but does accept width, height, padding, and margin (perfect for buttons and badges).

🛠️ Practice: Styling Form Inputs

css
/* Input styled with pristine Box Model mechanics */ .form-group input { display: block; width: 100%; padding: 12px 16px; background-color: #0d0f18; border: 1px solid #2a2e45; border-radius: 8px; color: #ffffff; font-size: 15px; outline: none; } /* Label spacing */ .form-group label { display: block; margin-bottom: 8px; font-size: 13px; font-weight: 500; color: #94a3b8; }