Lesson 5 of 6 · HTML + CSS

The CSS box model

Every element is laid out as a rectangular box. Understand content, padding, border and margin so you can control spacing without relying on random width and margin values.

Four parts of a box

The content area contains text, images or child elements. Padding adds space between the content and the border. The border surrounds the padding and content. Margin creates space outside the border, separating the element from its neighbours.

Padding is part of the element’s visible box; margin is outside it. This distinction matters when aligning cards, buttons and page sections.

Sizing with box-sizing

With the default content-box model, declared width applies to the content only. Padding and border are added to the final rendered size. That can make a card wider than the width you set.

box-sizing: border-box includes padding and border inside the declared width and height. A common baseline is * { box-sizing: border-box; } so width calculations are easier to reason about.

Borders, corners and shadows

Use border to define an edge, border-radius to round corners and box-shadow to add depth. These are visual effects; they do not replace good spacing or a clear content hierarchy.

Use consistent spacing values. A card with a 24-pixel padding and 16-pixel gap will often feel more intentional than one with unrelated values chosen for every element.

index.html
<div class="profile-card">
  <h1>Sam Rao</h1>
  <p>BCA student learning web development.</p>
  <a href="#">View profile</a>
</div>
style.css
* {
  box-sizing: border-box;
}

.profile-card {
  width: 320px;
  padding: 24px;
  margin: 30px auto;
  border: 1px solid #d8d8e8;
  border-radius: 18px;
  background: white;
  box-shadow: 0 12px 28px rgba(20, 20, 60, 0.12);
}

Try it yourself

The code examples above are for reference. Copy the relevant example into the editor, press Run, then change it and run it again.

Code Campus
Your turn

Style the profile card with a fixed maximum width, padding, border, rounded corners and a subtle shadow. Centre it horizontally using margin.

Show a hint
.profile-card {
  max-width: 360px;
  padding: 24px;
  margin: 30px auto;
  border: 1px solid #ddd;
  border-radius: 18px;
  box-shadow: 0 10px 24px rgba(0,0,0,.1);
}

#CodeCampus

Code Campus