#css #tutorial #beginner

Day 3: The Box Model

Day 3: Thinking Inside the Box

Every single element in HTML is a rectangular box. Understanding this box is key to layout.

The 4 Layers

From inside out:

  1. Content: The text or image itself.
  2. Padding: Space inside the box (between content and border). Background color applies here.
  3. Border: The line around the padding.
  4. Margin: Space outside the box (pushes other elements away). Transparent.
.box {
    content: "Hi";
    padding: 20px; /* Internal breathing room */
    border: 5px solid black; /* The shell */
    margin: 50px; /* Personal space */
}

The “Math Problem” (Box Sizing)

By default, CSS adds padding and border TO the width. If you set width: 200px + padding: 20px + border: 5px: Total Width = 200 + 20 + 20 + 5 + 5 = 250px.

This is annoying.

The Solution: border-box

Always reset this setting at the top of your CSS file. It tells the browser: “If I say 200px, I mean 200px TOTAL. Squeeze the padding inside.”

/* Apply to EVERYTHING */
*, *::before, *::after {
    box-sizing: border-box;
}

Auto Margins

Want to center a block horizontally?

.container {
    width: 800px;
    margin-left: auto;
    margin-right: auto;
    /* Shorthand: */
    margin: 0 auto; 
}

Homework for Day 3:

  1. Draw the box model on a piece of paper (seriously, it helps).
  2. Create two boxes in HTML.
  3. Give them thick borders and large padding.
  4. Experiment with box-sizing: content-box vs border-box to see the size change.

Day 4: Making text beautiful with Typography!