Log inSign up free
Mastering Modern CSS: From Zero to Pro
  1. Getting started

    1. CSS Lesson 1: What Is CSS?
    2. CSS Lesson 2: Selectors and Rules
    3. CSS Lesson 3: How CSS Works: The Cascade
    4. CSS Lesson 4: Colour and Backgrounds
    5. CSS Lesson 5: Typography and Text
    6. CSS Lesson 6: The Box Model
    7. CSS Lesson 7: Units and Sizing
    8. CSS Lesson 8: Display and Positioning
    9. CSS Lesson 9: Flexbox
    10. CSS Lesson 10: Grid
    11. CSS Lesson 11: Responsive Design
    12. CSS Lesson 12: Final Project
Mastering Modern CSS: From Zero to Pro

Getting started · Lesson 6 of 12 · 11 min read · By Jack

CSS Lesson 6: The Box Model

Every element on a web page is a rectangular box, even if it doesn't look like one. Text, images, links and headings are all boxes. CSS layout is mostly about sizing and spacing those boxes.

Downloads for this lesson

Sign up free (or log in) to download these files.

Learning goals: By the end, you'll be able to:

  • describe the four layers of every element's box
  • set padding, border and margin, using shorthand
  • predict an element's total size
  • use box-sizing: border-box
  • centre a block and understand margin collapsing
  • tell block, inline and inline-block apart

Part 1: Every element is a box (3 min)

Every element on a web page is a rectangular box, even if it doesn't look like one. Text, images, links and headings are all boxes. CSS layout is mostly about sizing and spacing those boxes.

Each box has four layers, from the inside out:

  1. Content: the text or image itself
  2. Padding: space between the content and the border, inside the box
  3. Border: a line around the padding
  4. Margin: space outside the border, separating this box from its neighbours

Padding shows the element's background colour. Margin is always transparent.

.card {  
  width: 300px;  
  padding: 20px;  
  border: 2px solid #1d4ed8;  
  margin: 16px;  
  background-color: #eff6ff;  
}

See it yourself. Open any page in your browser, right-click an element and choose Inspect. In the Computed tab, you'll see a diagram of the box. Hover over each layer and the page highlights it.

Quick check A. Which layer would you increase to push a box away from its neighbour? Which would you increase to give text breathing room inside a coloured box?


Part 2: Padding, border and margin (6 min)

Padding

.card {  
  padding: 20px;          /* all four sides */  
  padding-left: 40px;     /* one side */  
}

Padding is inside the border, so the background colour fills it. You use it to stop text touching the edges of a box.

Border

.card {  
  border: 2px solid #1d4ed8;     /* width style colour */  
  border-bottom: 1px dashed #9ca3af;  
  border-radius: 8px;  
}

Three parts: width, style and colour. The style is required. Without solid (or dashed, dotted and so on), no border shows. border-radius rounds the corners, and 50% on a square makes a circle.

Margin

.card {  
  margin: 16px;  
  margin-bottom: 2rem;  
}

Margin is outside the border and is always transparent. It controls the space between boxes.

LayerInside or outside?Shows background?
PaddingInside the borderYes
BorderThe edgeHas its own colour
MarginOutside the borderNo

Quick check B. You write border: 2px #1d4ed8;. Does a border appear?


Part 3: Shorthand values (4 min)

margin and padding accept one to four values. They go clockwise from the top:

You writeTopRightBottomLeft
margin: 10px;10101010
margin: 10px 20px;10201020
margin: 10px 20px 30px;10203020
margin: 10px 20px 30px 40px;10203040

A memory trick is TRouBLe: Top, Right, Bottom, Left.

With two values, the first is vertical (top and bottom) and the second is horizontal (left and right). Padding works the same way.

.button { padding: 8px 16px; }    /* 8px top and bottom, 16px left and right */

css_lesson6_shorthand_reference.csv has more examples.

Quick check C. What are the four sides of padding: 5px 10px 15px 20px;?

Quick check D. Write margin so the top and bottom are 0 and the left and right are 2rem.


Part 4: Width, height and box-sizing (6 min)

The surprise

By default, width sets the width of the content only. Padding and border are added on top.

.box {  
  width: 300px;  
  padding: 20px;  
  border: 2px solid black;  
}

Total width on screen: 300 + 20 + 20 (padding) + 2 + 2 (border) = 344px. That's wider than you asked for, which is why layouts often overflow by accident.

The fix: border-box

.box {  
  box-sizing: border-box;  
}

With border-box, width includes the padding and border. The same box is now exactly 300px wide, and the content area shrinks to 256px.

box-sizingwidth: 300px, padding 20px, border 2pxTotal width
content-box (default)content is 300px344px
border-boxcontent is 256px300px

The universal reset

Almost every modern stylesheet begins with this:

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

The * selector (Lesson 2) matches every element, so all boxes behave predictably. Put it at the top of your CSS file.

Try it on css_lesson6_box_size_calculator.csv, which has 8 worked scenarios you can check against your own browser.

min-width and max-width

.container {  
  max-width: 800px;  
}

max-width lets a box be narrower on small screens but never wider than the limit. It's usually better than a fixed width.

Quick check E. With content-box, what's the total width of a box with width: 200px, padding: 10px and border: 1px solid?

Quick check F. The same box with border-box: what's the total width, and how wide is the content?


Part 5: Centring and margin collapsing (4 min)

Centring a block

.container {  
  max-width: 800px;  
  margin: 0 auto;  
}

auto splits the leftover horizontal space equally, so the box sits in the middle. It needs two things: the element must be a block, and it must have a width or max-width. Otherwise it already fills the full width and there's nothing left to split.

Margin collapsing

When two blocks sit on top of each other, their vertical margins merge into the larger one:

.a { margin-bottom: 20px; }  
.b { margin-top: 30px; }

The gap between them is 30px, not 50px. This only affects vertical margins between neighbouring blocks. Horizontal margins and padding never collapse.

That's why you can set margin-bottom on every paragraph without the gaps doubling up.

Quick check G. The gap between two paragraphs: the first has margin-bottom: 16px, the second has margin-top: 24px. How big is the gap?


Part 6: Block, inline and inline-block (4 min)

The display property decides how a box behaves in the flow.

DisplayBehaviourWidth and height?Vertical margin?
blockStarts on a new line and fills the available widthYesYes
inlineFlows within a line of textNoNo, horizontal only
inline-blockFlows in a line but acts like a boxYesYes
noneRemoved from the page entirelyn/an/a

Block elements include div, p, h1 to h6, ul and section. Inline elements include span, a, strong and em.

This explains a very common beginner problem:

a {  
  width: 200px;     /* ignored: links are inline by default */  
  height: 50px;     /* ignored */  
}

The fix is to change the display:

a {  
  display: inline-block;  
  width: 200px;  
  height: 50px;  
}

display: none hides an element and its space. It's often used with a hover or a class change.

Quick check H. Which of these ignore width: <div>, <span>, <a>, <p>?


Part 7: Overflow, shadows and outlines (3 min)

overflow

When content is larger than its box:

ValueEffect
visibleSpills out (default)
hiddenClips the extra
scrollAlways shows scrollbars
autoScrollbars only when needed
.chat { height: 200px; overflow: auto; }

box-shadow

.card {  
  box-shadow: 0 2px 6px rgb(0 0 0 / 0.2);  
}

The values are x offset, y offset, blur, then colour (using the alpha colours from Lesson 4). Shadows don't take up space or change the layout.

outline

An outline is drawn outside the border and takes up no space. Browsers use it to show keyboard focus, so don't remove it without adding a clear replacement.


Common mistakes

MistakeFix
Box wider than expectedAdd the border-box reset
border: 2px #1d4ed8; with no styleAdd solid
margin: 0 auto doesn't centreThe element needs a width or max-width, and must be a block
Width or height ignored on a link or spanUse display: inline-block or block
Expecting vertical margins to add upNeighbouring vertical margins collapse
Using margin when you need paddingUse padding for space inside a coloured box
Fixed width on a containerPrefer max-width
Removing outline entirelyReplace it with a visible focus style
Confusing 2-value and 4-value shorthandRemember TRouBLe and "vertical, horizontal"

Key takeaways

  • Every element is a box made of content, padding, border and margin.
  • Padding is inside the border and shows the background, and margin is outside and is transparent.
  • Shorthand goes clockwise from the top, and two values mean vertical then horizontal.
  • By default, width is the content width only. Use box-sizing: border-box so it includes padding and border.
  • margin: 0 auto centres a block that has a width.
  • Vertical margins between neighbouring blocks collapse.
  • Inline elements ignore width and height. inline-block gives you both.
  • DevTools shows the box model for any element.

Exercises (15 min guided, plus extras)

1. Name the layers (2 min). What are the four layers of the box model, in order from the inside out?

2. Shorthand (3 min). Write each in four-value form (top, right, bottom, left):

  • a) padding: 12px;
  • b) margin: 8px 24px;
  • c) padding: 4px 8px 16px;

3. Calculate (3 min). For each, give the total width on screen:

  • a) content-box, width: 400px, padding: 25px, border: 5px
  • b) border-box, width: 400px, padding: 25px, border: 5px
  • c) border-box: how wide is the content in b)?

4. Spot the errors (3 min). Find four problems:

.card {  
  width: 300px;  
  padding: 20px  
  border: 2px #1d4ed8;  
  margin: 0 center;  
}  
  
a.btn {  
  width: 160px;  
  height: 48px;  
}

5. Predict (2 min). Two stacked paragraphs: the first has margin-bottom: 30px, the second has margin-top: 10px. What's the gap?

6. Build it: a profile card (12 min). Create card.html and card.css.

  1. Start card.css with the border-box reset.
  2. Add a <div class="card"> containing a name (h2), a job title (p), a short bio (p) and a link styled as a button.
  3. Give .card: max-width: 340px, padding: 24px, a border, border-radius, a background colour, a box-shadow, and margin: 40px auto so it's centred.
  4. Style the link as a button with display: inline-block, padding, a background colour (check contrast, Lesson 4), white text and rounded corners.
  5. Add margin-bottom to the name and job title for spacing.
  6. Open DevTools and inspect .card. Check the box diagram matches your numbers.

7. Challenge (4 min). Make two cards sit side by side using display: inline-block on each one. What do you notice about the small gap between them? Then try removing the whitespace between the tags in your HTML. (Lesson 7 will show a better method.)


Lesson 6 checkpoint

  • I can name the four layers of the box model.
  • I can read the box diagram in DevTools.
  • I can use 1, 2, 3 and 4 value shorthand.
  • I can calculate total width with content-box and border-box.
  • I add the border-box reset to my stylesheets.
  • I can centre a block with margin: 0 auto.
  • I understand margin collapsing.
  • I can fix a link or span that ignores width.


⬇️ ANSWER KEY (only scroll once you've tried the questions)

Quick check A: Increase the margin to push a box away from neighbours. Increase the padding to give content breathing room inside a coloured box.

Quick check B: No. A border needs a style such as solid. Write border: 2px solid #1d4ed8;.

Quick check C: Top 5px, right 10px, bottom 15px, left 20px.

Quick check D:

margin: 0 2rem;

Quick check E: 200 + 20 (padding) + 2 (border) = 222px.

Quick check F: Total width is 200px, and the content is 200 − 20 − 2 = 178px.

Quick check G: 24px. The margins collapse to the larger value, not 40px.

Quick check H: <span> and <a>, since both are inline by default. <div> and <p> are blocks.

Exercise 1: Content, padding, border, margin.

Exercise 2:

  • a) padding: 12px 12px 12px 12px;
  • b) margin: 8px 24px 8px 24px;
  • c) padding: 4px 8px 16px 8px;

Exercise 3:

  • a) 400 + 50 (padding) + 10 (border) = 460px
  • b) 400px
  • c) 400 − 50 − 10 = 340px

Exercise 4: The four problems:

  1. padding: 20px is missing a semicolon.
  2. border: 2px #1d4ed8; is missing a style such as solid.
  3. margin: 0 center; is invalid, because center isn't a margin value. Use margin: 0 auto;.
  4. a.btn has width and height, which are ignored because links are inline. Add display: inline-block;.

Corrected:

.card {  
  width: 300px;  
  padding: 20px;  
  border: 2px solid #1d4ed8;  
  margin: 0 auto;  
}  
  
a.btn {  
  display: inline-block;  
  width: 160px;  
  height: 48px;  
}

Exercise 5: 30px. The margins collapse to the larger one.

Exercise 6: Check that the reset is at the top, the card is centred with margin: 40px auto, the link button accepts its width and padding because it's inline-block, and DevTools shows 24px padding on all sides of the card.

Exercise 7: Inline-block elements are treated like words, so the whitespace between the tags in your HTML shows up as a small gap of a few pixels. Removing the whitespace (or using the layout tools in Lesson 7) closes it.

Keep track of your learning

This lesson comes with 4 downloads. Create a free account to unlock them and track your progress.

  • Track your progress through every course
  • Take the quizzes and see your score
  • Download the worksheets and resources
  • Get a certificate when you finish

Related reading on our blog

Rather have it done for you?

We build websites for small businesses

Everything in this course is what we do every day for local businesses: fast, mobile-friendly sites that are built to be found on Google. See our web design services or our website packages.