At the end of the previous lesson, The Blue Cup had links in the brand colour and a menu that marks the current page, but everything was still crammed together: the content takes up the full width of the window, the menu has no breathing room and the bookings card looks like just another link. To control space you need a central idea of CSS: every HTML element is drawn as a rectangular box, made up of four layers (content, padding, border and margin). In this lesson you'll learn to handle those layers, set widths and heights, use box-sizing: border-box to make measurements predictable, understand why two margins sometimes "merge" into one, and relate the display property to the block and inline flow you met in Module 2. You'll also see what to do when content doesn't fit in its box, the basic units of measurement and how to inspect any box in DevTools. In the project you'll give the whole site a structure with well-measured spacing.
Contents
- Every element is a box
- The four layers: content, padding, border and margin
- Writing margins, padding and borders
- Width and height
box-sizing: how measurements add up- Margin collapsing
displayand document flow- When content doesn't fit:
overflow - Basic units:
px,%,emandrem - Viewing the box in DevTools
- Project: The Blue Cup's structure
Every element is a box
To the browser, a page isn't text with tags, but a collection of rectangular boxes positioned relative to one another. Every header, section, p, a or img generates (at least) one box. Try the test you saw in the previous lesson, temporarily, at the end of styles.css:
When you reload any page you'll see a red rectangle around every element: sections contain headings and paragraphs, paragraphs contain links, the menu's li elements stack one below the other… It's the structure of your HTML made visible. Delete the rule when you've finished looking.
The four layers: content, padding, border and margin
Every box has four layers, from the inside out:
┌─────────────────────────────────────────────┐
│ margin │ ← outer space (transparent)
│ ┌─────────────────────────────────────┐ │
│ │ border │ │ ← line (visible if styled)
│ │ ┌─────────────────────────────┐ │ │
│ │ │ padding │ │ │ ← inner space (takes the background)
│ │ │ ┌─────────────────────┐ │ │ │
│ │ │ │ content │ │ │ │ ← text, images, child boxes
│ │ │ │ (width × height) │ │ │ │
│ │ │ └─────────────────────┘ │ │ │
│ │ └─────────────────────────────┘ │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────────┘| Layer | Property | What it is | Does it have a background? |
|---|---|---|---|
| Content | width, height |
The area where the text or child elements sit | Yes |
| Padding | padding |
Space between the content and the border | Yes: the background-color extends through it |
| Border | border |
The line surrounding the padding | It has its own colour |
| Margin | margin |
Space outside the border, separating the box from its neighbours | No: always transparent |
The practical difference between padding and margin is the key:
- Use
paddingwhen you want space inside a box with a background or border: the text of the bookings card shouldn't touch its border. - Use
marginwhen you want to separate a box from the others: space between one section and the next.
Writing margins, padding and borders
The four sides
margin and padding can be set side by side (margin-top, margin-right, margin-bottom, margin-left, and the same with padding-) or in shorthand, with between one and four values:
| Values | Example | Meaning |
|---|---|---|
| 1 | padding: 1rem; |
All four sides the same |
| 2 | padding: 1rem 2rem; |
Top and bottom 1rem; left and right 2rem |
| 3 | padding: 1rem 2rem 0.5rem; |
Top 1rem; left and right 2rem; bottom 0.5rem |
| 4 | padding: 1rem 2rem 0.5rem 0; |
Top, right, bottom, left (clockwise) |
A trick for remembering the order of four values: start at the top and go round clockwise (top, right, bottom, left).
Borders
border is shorthand for three properties: width, style and colour.
- The style is required for the border to be visible:
solid,dashed,dotted,doubleornone. - You can give a border to just one side with
border-top,border-right,border-bottomorborder-left, like the offer's side bar.
borderversusoutline: the focus outline you added in the previous lesson (outline) looks like a border, but isn't part of the box: it's drawn on top, takes up no space and moves nothing. That's why it's ideal for focus: appearing and disappearing doesn't shift the page.
Width and height
width and height set the dimensions of the box. But on the web, setting exact measurements usually causes problems: texts change length, users increase the font size and screens come in all sizes. That's why their limit variants are used most:
| Property | Typical use |
|---|---|
width |
Fixed or proportional measurements: width: 100% (the parent's full width) |
max-width |
Maximum width: the box narrows if needed, but never grows beyond that measurement. Ideal for limiting the length of lines of text |
min-width |
Minimum width |
height |
Hardly ever: the height should adapt to the content. Fixing it makes the text overflow |
min-height |
Minimum height, letting it grow if the content needs it |
A block box, by default, takes up all the available width of its parent and as much height as its content needs. That's almost always what you want.
Centring a box with margin: auto
Combining a maximum width with automatic side margins centres a block box in its container:
max-width: 64remlimits the width of the page.margin: 0 automeans: top and bottom margins of 0, and automatic side margins. The browser shares the remaining space equally between left and right, and the box ends up centred.
box-sizing: how measurements add up
A trick question: if a card has width: 300px, padding: 20px and border: 2px solid, how wide is it on screen?
With CSS's default behaviour, box-sizing: content-box, the width is only the content, and the padding and border are added on:
content-box: 2 + 20 + 300 + 20 + 2 = 344 px of visible width
border-box: 300 px (the content shrinks to 300 − 40 − 4 = 256 px)With box-sizing: border-box, the width includes the content, the padding and the border: the box measures exactly what you say, and it's the content that adapts.
content-box (default) |
border-box |
|
|---|---|---|
width includes |
Only the content | Content + padding + border |
| 300px card with 20px padding and 2px border | Takes up 344px | Takes up 300px |
Field with width: 100% and padding |
Overflows its container | Fits exactly |
| Ease of calculation | You have to add up in your head | What you write is what you see |
The case in the third row is very common: an input with width: 100% and a little padding sticks out of its form with content-box. That's why practically every project starts with this usual reset:
It applies border-box to every element and also to the boxes generated with ::before and ::after (remember that the universal selector doesn't include them). From here on, at The Blue Cup all measurements include padding and border.
Margin collapsing
The vertical margins of block boxes behave in a particular way: when two of them touch, they don't add up, but merge into a single one, the size of the larger. This is called margin collapsing.
Between siblings
Between a section and the h2 that opens the next one there isn't 3 + 1.5 = 4.5rem, but 3rem: the larger of the two. This is intentional: that way a paragraph with a 1em margin above and below doesn't leave 2em before the next paragraph, but 1em. The text stays evenly spaced without you having to think about it.
Between parent and child
The most confusing case: if a parent has no border or padding on one side, the margin of its first (or last) child passes through the parent and merges with the parent's margin.
If you give .welcome a background colour, you'll see that the background starts below the h1's top margin, as if that margin were outside the section. It is: it has merged with the section's margin.
How to avoid it when it gets in the way:
- Give the parent a
paddingor aborderon that side: the child's margin can no longer pass through it and stays inside. - Remove the margin from the first or last child (
margin-top: 0).
Be careful: as soon as you add padding to the parent, the child's margin stays inside and is added to the padding. That's what will happen in the project's bookings card: with padding: 1.5rem, the h2's top margin would add extra space at the top, which is why it's set to 0.
| Situation | Do they collapse? |
|---|---|
| Vertical margins of block siblings | Yes |
| Margin of a child and its parent with no border or padding on that side | Yes |
| Horizontal margins | Never |
| Elements inside a flex or grid container (upcoming lessons) | Never |
display and document flow
In Block and Inline Elements: div and span you saw that some elements start on a new line and take up the full width (block) and others flow within the text (inline). That behaviour is decided by the CSS display property, and every element has a default value in the browser's stylesheet: section, p and li are block; a, span, strong and img are inline.
| Value | Behaviour | width/height |
Vertical margins and padding |
|---|---|---|---|
block |
Starts on a new line and takes up all the available width | Respected | Push neighbouring boxes away |
inline |
Flows with the text, takes up only the size of its content | Ignored | The padding is painted, but doesn't push the lines above and below away; the vertical margin is ignored |
inline-block |
Flows with the text like inline, but on the inside is a block box |
Respected | Respected and push |
none |
No box is generated: the element disappears from the page and takes up no space | — | — |
The important thing: display changes how a box is presented, not what the element means. A link with display: block is still a link; an li with display: inline-block is still a list item. The HTML nesting rules don't change because of the CSS.
An example from the project: the menu links are inline. If you give them padding, the cream :hover background grows, but the vertical padding overlaps the neighbouring lines without pushing them away. With inline-block, the padding is fully respected and the clickable area really does grow:
Hiding elements: display: none, visibility and the hidden attribute
| Technique | Visible? | Takes up space? | Read by a screen reader? |
|---|---|---|---|
display: none |
No | No | No |
visibility: hidden |
No | Yes (leaves a gap) | No |
HTML hidden attribute |
No | No | No |
The HTML hidden attribute, which the menu's gluten-free filter uses to hide rows, works thanks to a rule in the browser's stylesheet equivalent to [hidden] { display: none; }. The problem: it's a browser rule, and any rule of yours that gives that element a display overrides it. If tomorrow you wrote tbody tr { display: table-row; } or had a hidden card with display: block, the hidden attribute would stop hiding it. That's why many projects add this to their base:
This is the legitimate use of !important announced in Inline, Internal and External CSS: a utility that must always work, whatever the rest of the stylesheet says. It will be the only one at The Blue Cup.
When content doesn't fit: overflow
If a box has a limited width or height and its content is larger, the content overflows: by default, it sticks out of the box and is drawn on top of whatever is outside. The overflow property decides what to do:
| Value | Result |
|---|---|
visible (default) |
The content sticks out of the box |
hidden |
Whatever doesn't fit is clipped and can't be seen |
scroll |
Scrollbars always appear |
auto |
Scrollbars appear only when needed |
There are also overflow-x and overflow-y to control each direction.
There's a real case at The Blue Cup: the cold brew recipe in news.html is in a pre, which keeps line breaks and doesn't wrap long lines. If a line is wider than the page, it overflows. The solution is a horizontal scrollbar only when needed:
Avoid overflow: hidden on text content: if the user increases the font size, whatever doesn't fit becomes inaccessible.
Basic units: px, %, em and rem
You've already used several units. These are the ones you need for now:
| Unit | Relative to | Example | Recommended use |
|---|---|---|---|
px |
Nothing: a fixed measurement (a reference pixel) | border: 1px solid |
Borders, outlines and fine details |
% |
The size of the containing element | width: 100% |
Widths proportional to the parent |
em |
The font size of the element itself | padding: 0.5em 0.75em |
Spacing that should grow with that element's text (buttons, cells) |
rem |
The font size of the root (html), usually 16px |
padding: 2rem |
General spacing and font sizes: consistent across the whole page |
Why rem for structural spacing? Because it's always based on the same value, the root font size: 2rem is the same in the header as in a figcaption with small text. And if the user sets their browser to a larger font size, the whole design grows in proportion. With px, the text would grow but the spacing wouldn't.
The menu tables use em, and that's fine: a cell's padding should be proportional to that cell's text. In Module 9, Responsive Web Design, you'll see units designed for the screen size.
Viewing the box in DevTools
DevTools shows the box model of any element:
- In Elements, hover over a tag: its box is highlighted on the page in colours (in Chrome and Edge, blue for the content, green for the padding, yellow for the border and orange for the margin).
- Select the element and open the Computed tab: at the top there's a diagram of concentric boxes with the real measurements of each layer. You can double-click a value to change it temporarily.
- In the Styles pane,
marginandpaddingvalues can be adjusted with the arrow keys (↑,↓) to find the measurement you're happy with.
It's the best way to understand a space you weren't expecting: it's almost always a default browser margin or a collapsed margin.
Project: The Blue Cup's structure
Open css/styles.css and add these rules in the sections indicated.
- Base (section 2)
Add these rules before the :focus-visible rule you already have:
/* ---------- 2. Base ---------- */
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
max-width: 64rem;
margin: 0 auto;
}
[hidden] {
display: none !important;
}
figure {
margin: 0 0 1.5rem;
}
pre {
overflow-x: auto;
}- The
box-sizingreset makes every measurement include padding and border. bodylimits the page to 64rem (1024 pixels with the default font size) and centres it. The browser gives thebodyan 8-pixel margin by default;margin: 0 autoreplaces it. The header, the content and the footer line up in a single column.[hidden]protects the menu filter and any other use ofhidden.figureremoves the 40-pixel indent that the browser gives figures by default (you were told about it in main and figure): the gallery and the reviews line up with the rest of the text, with a bottom margin to separate them.pregives the recipe horizontal scrolling when it doesn't fit.
- Header and menu (section 4)
Add the header rules at the start of the section and extend the menu ones. The section now looks like this:
/* ---------- 4. Header and menu ---------- */
body > header {
padding: 1rem 2rem;
border-bottom: 4px solid #1f4e79;
}
.logo {
margin: 0;
}
.logo img {
display: block;
}
.menu {
list-style: none;
margin: 0.75rem 0 0;
padding-left: 0;
}
.menu li {
display: inline-block;
}
.menu a {
display: inline-block;
padding: 0.5rem 0.75rem;
color: #1f4e79;
font-weight: bold;
text-decoration: none;
}
/* .menu a:not(…):hover and .menu a[aria-current="page"], unchanged */body > header(notheader, so as not to affect the news headers): inner padding and a thick bottom line in the brand blue..logoremoves the margins of the paragraph containing the logo..logo imgwithdisplay: block: an image isinlineand sits on the text baseline, like a letter, so it leaves a small gap underneath (the space for the descenders of letters such as "g" or "p"). As a block, the gap disappears..menu liwithinline-block: the menu items sit side by side, like words on a line. Your menu is now horizontal..menu awithinline-blockand padding: each link is a comfortable clickable area, with space around the text. The cream:hoverbackground and the current-page line extend across that whole area.
- Structure:
main, sections and footer (section 5)
main, sections and footer (section 5)/* ---------- 5. Structure: main, sections and footer ---------- */
main {
padding: 2rem;
}
main > section,
main > article,
main > aside {
margin-bottom: 3rem;
}
body > footer {
padding: 2rem;
border-top: 4px solid #1f4e79;
}mainhas the same side padding (2rem) as the header: the text in all three areas lines up at the same distance from the edge.- The direct children of
main(the home page sections, the news items, the newsletter…) are separated by 3rem. The bottom margin collapses with the top margin of the nexth2, so the separation is exactly 3rem. body > footer(not thefooterelements of the articles) gets padding and a top line that matches the header's.
- Components: card, offer and reviews (section 6)
/* ---------- 6. Components: card, offer and reviews ---------- */
.card {
display: block;
max-width: 32rem;
padding: 1.5rem;
border: 2px solid #1f4e79;
background-color: #dce6f0;
text-decoration: none;
}
.card h2 {
margin-top: 0;
}
.card p {
margin-bottom: 0;
}
.featured {
padding: 1rem 1.5rem;
border-left: 6px solid #1f4e79;
background-color: #fff6e0;
}
.review {
padding: 1rem 1.5rem;
border: 1px solid #c8d3e0;
}
.review blockquote {
margin: 0 0 0.75rem;
}- The booking card (
a.cardin the#booksection) is a link that wraps anh2and ap. Sinceaisinline, its box doesn't wrap blocks properly: the border and background would be painted oddly around each line. Withdisplay: block, the link is a real box, with a maximum width of 32rem, inner padding, a blue border and a light blue background. What's more, the whole card is clickable. .card h2and.card p: with the padding, the margins of the first and last child no longer collapse with the card and would be added to the padding. They're removed so that the inner space is exactly 1.5rem on all four sides..featured(the offer'saside) becomes a block with a cream background and a blue bar on the left..reviewdraws each review as a box with a soft border; the bottom margin is already provided by thefigurerule in the base. Theblockquoteloses its default indent (also 40 pixels) and is separated from the quotation's caption.
- Check it
- Open
index.html. The page is centred in a column, the header has breathing room and a blue line underneath, the menu is horizontal, the sections are separated and the booking card stands out as a block. Hover over it: the background changes to cream, becausea:hover(0, 1, 1) is more specific than.card(0, 1, 0). It's an effect you weren't aiming for, but it works well as visual feedback. - In
news.html, check that the article headers don't have the blue line: only the site header does. If the browser window is narrow, the cold brew recipe shows a horizontal scrollbar. - In
menu.html, tick and untick the gluten-free filter: it still works. - Select the booking card in Elements and look at its diagram in Computed: the total width includes the padding and the border (thanks to
border-box). - Experiment: temporarily comment out the
.card h2rule and watch the space at the top of the card grow.
Common Mistakes and Tips
- Confusing
paddingandmargin: if you want the background to extend, it's padding; if you want to separate boxes, it's margin. - Forgetting the border style:
border: 2px #1f4e79isn't visible;solidis missing. - Setting
heighton boxes with text: as soon as the text grows, it overflows. Usemin-heightor let the height adapt. - Working without
box-sizing: border-box: widths "don't add up" and fields at 100% stick out of the form. - Being surprised by margin collapsing: if a space isn't the sum you expected, look in DevTools; two margins have probably merged, or a child's margin has passed through its parent.
- Giving
widthor vertical margins to aninlineelement and nothing happening: change it toinline-blockorblock. - Hiding something a screen reader should read with
display: none: it hides it from everyone. (There are techniques for hiding things only visually; you'll see them in Web Accessibility Basics.) overflow: hiddento "fix" an overflow: the content is still there, but nobody can see it.- Tip: when you can't work out where a space comes from, the Computed diagram in DevTools tells you in seconds.
Exercises
Exercise 1. Calculate the total width this box takes up on screen, first with content-box and then with border-box. Include the margin in the total space it takes up in the row:
Exercise 2. Two consecutive paragraphs have these rules. How much vertical space is there between them? And what if the second were display: inline-block?
Exercise 3. Style the aside#newsletter in news.html as a box with a #f7f7f7 background, a 1px #c8d3e0 border, 1.5rem of padding, a maximum width of 32rem, and without the extra space at the top that the h2 opening it would leave. Use the featured class… or not? Explain which selector you'd use.
Solutions
Solution 1.
content-box: the visible width is 3 + 20 + 400 + 20 + 3 = 446px. With the margins, it takes up 15 + 446 + 15 = 476px of the row.border-box: the visible width is 400px (the content stays at 400 − 40 − 6 = 354px). With the margins, it takes up 15 + 400 + 15 = 430px.
The margin is never part of width, not even with border-box: it's outer space.
Solution 2. With two block paragraphs, the vertical margins collapse: the space is the larger of the two, 24px, not 40px. If the second were inline-block, they'd no longer be two sibling block boxes: collapsing doesn't happen and the margins add up, although the exact result depends on how the box sits within its line. In general, collapsing only happens between vertical margins of block boxes in normal flow.
Solution 3. Reusing featured isn't a good idea: that class already means "featured offer" (cream background and blue bar), and the newsletter is something else. Mixing them would mean fighting with its styles. There are two reasonable options:
- Add a dedicated class in the HTML,
<aside class="newsletter-box" id="newsletter">, and write.newsletter-box. It's the cleanest option and consistent with the convention of naming classes after content. - Use
#newsletter. It works, but it styles with an ID, with its high specificity. It would only be acceptable as a one-off tweak.
.newsletter-box {
max-width: 32rem;
padding: 1.5rem;
border: 1px solid #c8d3e0;
background-color: #f7f7f7;
}
.newsletter-box h2 {
margin-top: 0;
}The h2 loses its top margin because, with the padding, that margin would no longer collapse and would be added to the padding.
Conclusion
You now understand that every element is a box with four layers (content, padding, border and margin) and you know how to write their properties side by side or in shorthand, limit widths with max-width, centre with margin: auto and make measurements predictable with box-sizing: border-box. You know about margin collapsing between siblings and between parent and child, the relationship between display (block, inline, inline-block, none) and the flow you studied in Module 2, how to control overflow with overflow, when to use px, %, em and rem, and how to read any box in DevTools. The Blue Cup now has a structure with well-measured spacing: the page centred in a column, the header and footer with padding and brand-coloured lines, a horizontal menu with comfortable clickable areas, separated sections, the booking card as a block with a background, the offer highlighted and the reviews framed, and the hidden attribute protected. But the text still uses the browser's default typography, the footer has no colour of its own, the forms are hard to read and the colour palette is repeated as hexadecimal values throughout the stylesheet. In the next lesson, Styling HTML Elements, you'll give the whole site careful typography, a consistent palette with CSS variables, readable buttons and forms and a gallery with well-presented captions.
HTML Course
Module 1: Introduction to HTML
- What Is HTML?
- Setting Up Your Work Environment
- Basic Structure of an HTML Document
- Tags, Elements and Attributes
- Creating Your First HTML Page
- File Organisation and Paths
Module 2: Text Formatting in HTML
- Headings and Paragraphs
- Text Formatting Tags
- Lists: Ordered, Unordered and Description Lists
- Block Quotes and Preformatted Text
- Block and Inline Elements: div and span
Module 3: Links and Media in HTML
- Creating Hyperlinks
- Special Links: Anchors, Email, Phone and Downloads
- Adding Images
- Embedding Videos
- Using the Audio Element
Module 4: Tables in HTML
- Basic Table Structure
- Table Head, Body and Foot
- Merging Cells: colspan and rowspan
- Accessible Tables: caption, scope and headers
- Styling Tables
Module 5: Forms in HTML
- Creating a Basic Form
- Form Elements: input, textarea and select
- HTML5 Input Types
- Labels and Grouping: label, fieldset, legend and datalist
- Form Attributes and Validation
- Submitting Forms
Module 6: HTML5 Semantic Elements
- Introduction to Semantic HTML
- header, nav and footer
- article, section and aside
- main and figure
- Other Semantic Elements: time, address, details and dialog
Module 7: Advanced HTML Techniques
- HTML Entities
- Using iframes
- Data Attributes
- Metadata: meta, SEO and Open Graph
- Microdata and Structured Data
- Graphics in HTML: SVG and canvas
Module 8: Integrating HTML and CSS
- Linking CSS to HTML
- Inline, Internal and External CSS
- Basic CSS Selectors
- The Box Model
- Styling HTML Elements
- Introduction to Layout with Flexbox and Grid
Module 9: Responsive Web Design
Module 10: Best Practices and Accessibility
- HTML Best Practices
- Validating HTML Code
- Web Accessibility Basics
- Using ARIA Roles and Attributes
- Accessibility Testing
- Performance and Resource Loading
