Until now, all The Blue Cup's boxes have been placed according to normal flow: block elements one below the other; inline elements one after the other like words. With inline-block you got a horizontal menu, but the logo is still above the menu, the gallery products are stacked in a long column and the home page offer appears between two sections instead of beside the content. Layout means deciding where each block of the page goes, and CSS now has two tools designed for it: Flexbox, for placing elements in a row or a column, and Grid, for organising them in a grid of rows and columns at the same time. In this lesson you'll learn a little history (why layouts are no longer built with tables or float), the essential properties of each system, when to use one or the other and why the semantic structure you've built throughout the course makes layout much simpler. In the project you'll give The Blue Cup its desktop layout and bring the module to a close.

Contents

  1. Why not tables or float: a little history
  2. Flexbox: container and items
  3. Flexbox's two axes
  4. Flex container properties
  5. Grid: rows and columns at once
  6. Columns with fr and repeat()
  7. Named areas: grid-template-areas
  8. Flexbox or Grid?
  9. Semantic structure makes layout easier
  10. Flexbox and Grid in DevTools
  11. Project: The Blue Cup's layout

Why not tables or float: a little history

For years, CSS had no tools for layout, and developers made do with what there was:

Era Technique Problem
Late 1990s Tables (table) to position the header, columns and footer Mixes content and presentation; screen readers announce a "table" that contains no data; huge, rigid code. You saw this in Basic Table Structure: tables are for data only
2000s float, designed to let text wrap around an image, used to put columns side by side It was a hack: floats had to be "cleared", columns didn't have equal heights, vertical centring was almost impossible
Around 2010 inline-block for menus and grids The whitespace between tags in the HTML leaves gaps between the boxes; vertical alignment is fragile
From the mid-2010s Flexbox and Grid, designed for layout Today every browser supports them

float isn't obsolete: it's still useful for what it was invented for, letting an image sit to one side with the text wrapping around it. But for positioning the blocks of a page, the modern answer is Flexbox or Grid.

Flexbox: container and items

Flexbox (Flexible Box Layout) is switched on with a single declaration on the parent:

.menu {
  display: flex;
}

From that moment on there are two roles:

  • The flex container: the element with display: flex, here ul.menu.
  • The flex items: its direct children, here the li elements. Only direct children: the a elements inside each li aren't affected.

With just that declaration, the li elements are placed in a row, side by side, taking up the width their content needs, and all with the same height. No strange gaps, no tricks.

Without flex (normal flow):     With display: flex:
┌──────────────────────┐        ┌──────┬──────┬──────────┬─────────┐
│ Home                 │        │ Home │ Menu │ Bookings │ Gallery │ …
├──────────────────────┤        └──────┴──────┴──────────┴─────────┘
│ Menu                 │
├──────────────────────┤
│ Bookings             │
└──────────────────────┘

Flexbox's two axes

Flexbox works with two perpendicular axes, and almost all its properties refer to one of them:

                  cross axis
                     ▲
                     │
   ┌─────────────────┼──────────────────────────────┐
   │  ┌─────────┐ ┌──┴──────┐ ┌─────────┐           │
───┼─▶│  item   │ │  item   │ │  item   │ ──────────┼──▶  main axis
   │  └─────────┘ └─────────┘ └─────────┘           │      with flex-direction: row
   └────────────────────────────────────────────────┘
            container with display: flex
  • The main axis is the direction in which the items are placed. With flex-direction: row (the default), it's horizontal, from left to right.
  • The cross axis is the perpendicular one. With row, it's vertical.

If you switch to flex-direction: column, the axes swap: the main axis becomes vertical. That's why the properties aren't called "horizontal" and "vertical", but refer to axes instead:

Property Aligns on the… With row it means
justify-content Main axis Horizontal
align-items Cross axis Vertical

Flex container properties

flex-direction

Value The items are placed
row (default) In a row, from left to right
column In a column, from top to bottom
row-reverse, column-reverse In reverse order

Be careful with the reverse values (and with the order property): they change the visual order, but the HTML order, the one followed by the keyboard and screen readers, stays the same. If the order matters, change it in the HTML.

justify-content: distribution along the main axis

Value Result (with row)
flex-start (default) All at the start (on the left)
flex-end All at the end (on the right)
center Centred
space-between The first at the start, the last at the end and the remaining space shared out between them
space-around / space-evenly Space also shared out around the ends
flex-start:     [A][B][C]·················
center:         ·········[A][B][C]········
space-between:  [A]··········[B]·········[C]

space-between is the classic choice for a header: the logo on the left and the menu on the right.

align-items: alignment on the cross axis

Value Result (with row)
stretch (default) All stretch to the height of the tallest
flex-start Aligned to the top
center Centred vertically
flex-end Aligned to the bottom
baseline Aligned by the text baseline

Vertical centring, which for years was one of CSS's great headaches, is now a single line: align-items: center.

gap: the space between items

.menu {
  display: flex;
  gap: 0.25rem;
}

gap puts space only between the items, not before the first or after the last. It's much cleaner than giving each item a margin and then removing it from the last one.

flex-wrap: moving on to the next line

By default (nowrap), Flexbox fits every item onto a single line, shrinking them if necessary, even if they overflow. With flex-wrap: wrap, when they don't fit, the ones left over move on to the next line:

.menu {
  display: flex;
  flex-wrap: wrap;
}

If the window narrows, the menu links drop onto a second line instead of sticking out of the page.

Adjusting a single item: align-self

The properties above go on the container and affect every item. If just one item needs to be aligned differently, you give it align-self (with the same values as align-items). You'll use it in Grid, where it works the same way.

Grid: rows and columns at once

Flexbox thinks in one dimension: a row (or a column) of items sharing out the space. Grid (CSS Grid Layout) thinks in two dimensions: you define a grid of columns and rows, and the children are placed in its cells.

.product-gallery {
  display: grid;
  grid-template-columns: 300px 300px 300px;
  gap: 1.5rem;
}
  • display: grid turns the element into a grid container, and its direct children into grid items.
  • grid-template-columns defines the columns: here, three of 300 pixels.
  • The items are placed automatically, from left to right and top to bottom: a fourth item would start a new row. The rows create themselves, as tall as their content.
  • gap works just as in Flexbox: space between columns and between rows. With two values, gap: 1rem 2rem, the first is between rows and the second between columns.

Note: although it's called a "grid", it has nothing to do with table. It's a way of presenting any content; the HTML is still a list, some sections or whatever it may be.

Columns with fr and repeat()

Fixed-pixel columns have the usual problem: if the container is narrower, they overflow. Grid introduces its own unit, fr (fraction): a share of the available space.

Definition Result
1fr 1fr 1fr Three equal columns sharing the full width
2fr 1fr Two columns: the first twice as wide as the second (2/3 and 1/3)
16rem 1fr A fixed 16rem column and another taking up the rest
repeat(3, 1fr) The same as 1fr 1fr 1fr, written in shorthand
repeat(4, 1fr) Four equal columns

fr shares out the space left over after subtracting the gap and any fixed columns, so you never have to do any maths to make everything fit.

.product-gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
}

Three equal columns, always fitted to the width of the container. The photos, which are 400 pixels wide, shrink thanks to the max-width: 100% from the previous lesson.

Named areas: grid-template-areas

To lay out a page with areas of different sizes, Grid lets you draw the grid with names:

.home {
  display: grid;
  grid-template-columns: 2fr 1fr;
  grid-template-areas:
    "welcome       welcome"
    "bakery        offer"
    "book          offer"
    "opening-hours opening-hours"
    "reviews       reviews";
}
  • Each quoted string is a row; each word, a column. With two columns, each row has two names.
  • A name repeated horizontally makes the area span several columns ("welcome" spans both).
  • A name repeated vertically makes it span several rows ("offer" spans two rows, beside "bakery" and "book").
  • The extra spaces between names are only there to line up the drawing and make it easier to read.
  • Each area must be a rectangle: you can't make "L" shapes.

Then each element is placed in its area with grid-area:

.welcome {
  grid-area: welcome;
}

The result is a plan of the page that can be read at a glance:

┌───────────────────────────────────────────────┐
│                    welcome                    │
├──────────────────────────────┬────────────────┤
│            bakery            │                │
├──────────────────────────────┤     offer      │
│             book             │                │
├──────────────────────────────┴────────────────┤
│                 opening-hours                 │
├───────────────────────────────────────────────┤
│                    reviews                    │
└───────────────────────────────────────────────┘
          2fr                        1fr

Flexbox or Grid?

They don't compete: they complement each other, and it's normal to use both on the same page.

Criterion Flexbox Grid
Dimensions One: row or column Two: rows and columns
What's in charge The content: each item takes what it needs and the rest is shared out The design: you define the grid and the content is placed in it
Alignment across rows Each line is independent: the items in one row don't line up with those in the next Columns line up across all rows
Typical cases Menus, button bars, a header with logo and menu, aligning an icon with some text, a footer with several blocks in a row Galleries and catalogues, the overall structure of a page, two-column forms, any design with aligned rows and columns
At The Blue Cup Header and menu Product gallery and home page

A rule of thumb: if you're thinking "put these things side by side", use Flexbox; if you're thinking "place these things in this grid", use Grid.

Semantic structure makes layout easier

Notice how little you'll touch the HTML in the project: a single class. Everything else is already there thanks to the previous modules:

  • Flexbox and Grid act on direct children. Since the header contains exactly two children, p.logo and nav, putting the logo on the left and the menu on the right is immediate. If the header were a tangle of nested div elements, you'd have to untangle it first.
  • The menu is a list (ul.menu with its li elements): its children are exactly the items that need to go in a row.
  • The gallery is a list of figure elements: each li is a cell in the grid.
  • The home page is divided into section and aside elements with clear names (welcome, bakery, offer…): those blocks are exactly the areas on the plan. The aside already says "complementary content", which is what usually goes in a side column.
  • The HTML order is the logical reading order. Grid places the areas visually wherever you like without changing that order, which is the one followed by the keyboard and screen readers. That's why the visual placement should, as far as possible, respect the order of the code.

HTML designed around meaning is, at the same time, HTML that's easy to lay out.

Flexbox and Grid in DevTools

In the Elements tab, flex and grid containers show a small badge (flex or grid) next to their tag. Clicking it draws an overlay on the page with the grid lines, the area names and the gap spaces. In the Styles pane, next to display: flex there's a button that opens a visual editor for trying out justify-content and align-items values with a click. They're the best way to understand what each property is doing.

Project: The Blue Cup's layout

  1. Header with logo and menu on one line (section 4)

In section 4 of styles.css, extend the header rule, replace the .menu rule and delete the .menu li { display: inline-block; } rule, which is no longer needed:

/* ---------- 4. Header and menu ---------- */

body > header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
  padding: 1rem 2rem;
  border-bottom: 4px solid var(--color-brand);
}

.logo {
  margin: 0;
}

.logo img {
  display: block;
}

.menu {
  display: flex;
  flex-wrap: wrap;
  gap: 0.25rem;
  margin: 0;
  padding-left: 0;
  list-style: none;
}

/* .menu a, .menu a:not(…):hover and .menu a[aria-current="page"], unchanged */
  • The header is a flex container with two children: the logo and the nav. justify-content: space-between pushes them to the ends and align-items: center centres the menu vertically relative to the logo, which is taller.
  • flex-wrap: wrap and gap: 1rem: if they don't fit on one line, the menu drops below the logo with some space between them, instead of overflowing.
  • The menu is another flex container, nested inside the first: the nav is an item of the header, and the ul it contains positions its own children. The li elements line up in a row without inline-block, without the small gaps left by the line breaks between tags in the HTML, and with an exact space between links thanks to gap.
  • The top margin you gave the menu in The Box Model no longer makes sense: it's now beside the logo, not below it.

  1. Product gallery in a grid (section 9)

Extend the list rule and make the tiles the same height:

.product-gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
  list-style: none;
  padding-left: 0;
}

.product-gallery figure {
  height: 100%;
  margin: 0;
  padding: 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius);
  background-color: var(--color-light-grey);
}
  • The three products sit in a row of three equal columns, with 1.5rem between them. If the bakery adds a fourth product tomorrow, it will automatically start a second row, aligned with the first.
  • In a grid row, all the cells (the li elements) have the same height. With height: 100%, each figure fills its whole cell, and the tiles end up the same size even if one name is longer and takes up two lines.
  • The figure loses its bottom margin: the separation is now provided by gap.

  1. The home page: main content and side column (section 5)

This is the only change to the HTML. In index.html, add the home class to the main:

    <main id="content" class="home">

And in section 5 of the stylesheet, after the main rules:

.home {
  display: grid;
  grid-template-columns: 2fr 1fr;
  grid-template-areas:
    "welcome       welcome"
    "bakery        offer"
    "book          offer"
    "opening-hours opening-hours"
    "reviews       reviews";
  gap: 1.5rem 2rem;
}

.home > * {
  margin-bottom: 0;
}

.home > .welcome {
  grid-area: welcome;
}

.home > #bakery {
  grid-area: bakery;
}

.home > .featured {
  grid-area: offer;
  align-self: start;
}

.home > #book {
  grid-area: book;
}

.home > #opening-hours {
  grid-area: opening-hours;
}

.home > #reviews {
  grid-area: reviews;
}

Explanation:

  • The home class identifies the home page's main, the only one with this layout. The other pages keep their main in normal flow.
  • The plan: the welcome across the full width; below it, on the left (two thirds), the bakery and the booking card, and on the right (one third), the breakfast offer as a side column; then the opening hours and the reviews across the full width, because the opening hours table has eight columns and needs all the space.
  • gap: 1.5rem 2rem: 1.5rem between rows and 2rem between columns.
  • .home > * removes the bottom margin that section 5 gave the children of main. Inside a grid, margins don't collapse (you saw this in The Box Model), and the separation is already provided by gap. The .home > * selector (0, 1, 0) beats main > section (0, 0, 2).
  • grid-area places each block in its area. For bakery, book, opening-hours and reviews, the IDs that already exist as anchors are used: this is the exception the project convention allows, a specific tweak on a single page, and always preceded by .home > to make its scope clear. Adding classes that duplicated the ID would add nothing.
  • align-self: start on the offer: by default, a grid item stretches to fill its whole area, and the cream box would extend down to the end of the booking card. With start, it's only as tall as its content needs and stays at the top.

  1. Check it

  1. Open index.html with the browser window maximised. The logo is on the left and the menu on the right, at the same height. Below the welcome, the bakery and the booking card fill the main column, and the breakfast offer appears to their right. The opening hours and the reviews span the full width.
  2. Tab through the home page: the focus follows the HTML order (welcome, bakery, offer, booking…), which matches a logical reading order.
  3. Open gallery.html: the three products in a row, with tiles of the same height.
  4. In DevTools, click the grid badge on the home page's main: you'll see the grid lines and area names drawn over the page. Do the same with the header's flex badge.
  5. Narrow the window gradually. The menu drops below the logo (thanks to flex-wrap), but the gallery stubbornly sticks to three ever-narrower columns and the home page offer turns into a tiny column. Remember what you see: it's the problem for the next module.

Project status at the end of the module

File What's new in Module 8
css/styles.css New. The site's single stylesheet, organised into nine sections
All seven pages <link rel="stylesheet" href="css/styles.css"> in the head, after the description. No style attributes or <style> elements
menu.html Without the temporary <style> block: its rules now live in section 7 of the stylesheet
index.html main with the home class; the opening hours table gets the table styles
bookings.html Without the <br> elements before the small hints and after the comments label: the CSS places them below each field

Final structure of css/styles.css:

Section Main contents
1. Variables :root with the palette (--color-brand, --color-border, --color-soft, --color-cream, --color-light-grey), the text colours (--color-text, --color-text-muted, --color-visited, --color-white), the --font-body and --font-headings stacks, and --radius
2. Base box-sizing: border-box reset; html with a grey background; centred body (64rem) with typography, line height and colours; [hidden] with !important; figure, pre with overflow-x; img, video with max-width: 100%; :focus-visible
3. Typography and links Blue serif headings with sizes in rem; small, figcaption, li::marker; offer prices; links with :visited and :hover states; abbr[title]
4. Header and menu Flex body > header (logo and menu at the ends); flex .menu with gap; menu links with padding; current page with [aria-current="page"]
5. Structure main with padding; spacing between sections; .home with grid-template-areas; blue body > footer with white links and focus
6. Components .card, .featured, .review
7. Tables The rules from Styling Tables, with variables
8. Forms and buttons font: inherit; fieldset and legend; labels; block fields with a contrasting border; small hints; primary button and secondary button[type="button"]
9. Gallery .product-gallery in a three-column grid with tiles of equal height

Conventions established in the module: all the CSS in css/styles.css; sections from general to specific; styles with type, class and attribute selectors (IDs only for placing the areas of a specific page, preceded by their container); body > header and body > footer so as not to affect the headers and footers of articles; repeated colours and measurements always in variables named after their role; font sizes and general spacing in rem; no !important except on [hidden]; focus always visible.

Common Mistakes and Tips

  • Putting display: flex on the element you want to move instead of on its parent: Flexbox and Grid are switched on in the container and position the children.
  • Expecting it to affect grandchildren: only direct children are flex or grid items. To position those at a lower level, that child must itself be a container (like the nav and its ul.menu).
  • Confusing justify-content and align-items: the first works on the main axis, and the second on the cross axis. With flex-direction: column, they swap.
  • Forgetting flex-wrap: wrap: without it, items shrink or overflow rather than moving to another line.
  • Margins on every item to separate them: use gap.
  • grid-template-areas areas that aren't rectangles, or rows with different numbers of names: the whole declaration is ignored and the grid doesn't form.
  • Visually reordering things that have a logical order (with order, row-reverse or by placing areas far from their position in the HTML): anyone navigating with a keyboard or screen reader goes through a different order.
  • Going back to tables or float for layout because an old tutorial does it that way.
  • Tip: sketch the page plan on paper first, with boxes and names. If the HTML already has an element for each box, the layout will be almost straightforward.

Exercises

Exercise 1. Lay out the page footer (body > footer) as a flex row: the paragraph with the icon and the name, the address, the short opening hours and the privacy link, side by side with 2rem between them, wrapping onto another line if they don't fit, and aligned at the top. The copyright small must sit on its own line, below everything else. (Hint: a flex item can take up the full width with flex-basis: 100%.)

Exercise 2. Put the two reviews in #reviews (the figure.review elements) side by side, in two equal columns with 1.5rem between them. Flexbox or Grid? Bear in mind that the section also contains an h2 and a paragraph with links that shouldn't go into the columns.

Exercise 3. In news.html, the main contains the search form, the news article elements and the aside#newsletter. Use grid-template-areas to design a layout with the title and the search form across the full width at the top, the news in a main column and the newsletter in an 18rem side column. Write the plan and explain what problem you run into with the multiple article elements.

Solutions

Solution 1.

body > footer {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 1rem 2rem;
  padding: 2rem;
  background-color: var(--color-brand);
  color: var(--color-white);
}

body > footer p,
body > footer address {
  margin: 0;
}

body > footer small {
  flex-basis: 100%;
}
  • display: flex on the footer places its direct children in a row: the paragraphs, the address and the small.
  • align-items: flex-start aligns them at the top, since the address takes up several lines and the others one.
  • gap: 1rem 2rem: 2rem between blocks on the same line and 1rem between lines.
  • The margins of the paragraphs and the address are removed: in a flex container they don't collapse and would be added to the gap.
  • flex-basis: 100% makes the small need the full width and, since there's flex-wrap, it moves onto its own line at the end.

Solution 2. Grid is the natural choice: "two equal columns" is a grid. The problem is that the columns should apply only to the reviews, not to the h2 or the paragraph. There are two solutions:

  1. Make the grid on the section and have the heading and paragraph span both columns with grid-column: 1 / -1 (from the first grid line to the last):

    #reviews {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 1.5rem;
    }
    
    #reviews > h2,
    #reviews > p {
      grid-column: 1 / -1;
    }
    
  2. Wrap the two figure elements in a div class="review-list" and make the grid on that div. This is one of the cases where a div is justified: grouping for layout, with no meaning of its own (the convention from Introduction to Semantic HTML).

    .review-list {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 1.5rem;
    }
    

The second is easier to read and doesn't depend on an ID. Remember to remove the bottom margin of the figure elements inside the grid (.review-list figure { margin: 0; }), because the separation is already provided by gap.

Solution 3. One possible plan, with a news class on the main:

.news {
  display: grid;
  grid-template-columns: 1fr 18rem;
  grid-template-areas:
    "header   header"
    "articles newsletter";
  gap: 2rem;
}

The problem: grid-template-areas places elements, and there are several article elements that are direct children of the main. If they all had grid-area: articles, they would overlap in the same cell. The same happens with the h1 and the search, which are two elements for a single "header" area. Solutions:

  • Group them in the HTML: a div wrapping the article elements (grouping for layout) and another, or a header, wrapping the h1 and the search form. Then each area contains exactly one element.
  • Or give up on areas and use line-based placement: the article elements in column 1 (grid-column: 1) and the aside in column 2 spanning all the rows (grid-column: 2; grid-row: 2 / span 10), which is a little more advanced.

It's a good example of how grid-template-areas works best when each area corresponds to a single element, as on the home page. Designing the HTML with those blocks in mind makes layout easier.

Conclusion

With this lesson you complete the Integrating HTML and CSS module. You've learnt why tables and float stopped being used for layout, how to place elements in a row or a column with Flexbox (container and items, main and cross axes, flex-direction, justify-content, align-items, gap and flex-wrap) and how to organise them in rows and columns with Grid (grid-template-columns with fr and repeat(), gap and named areas with grid-template-areas), and how to choose between the two depending on whether you're thinking in one dimension or two. Over the course of the module, The Blue Cup has gone from the browser's default look to a complete design: a single css/styles.css stylesheet linked from every page, with no scattered styles, organised into sections and based on variables; selectors that take advantage of semantics, such as aria-current or body > header; a predictable box model with border-box; consistent typography, palette and forms; and a layout with the header on one line, the gallery in a grid and a home page with a side column. If you'd like to go deeper into CSS (animations, transforms, effects, architecture for large stylesheets), the portal has a dedicated CSS course. But there's a problem you saw when you narrowed the window: this design is built for a desktop. On a phone, the gallery insists on three tiny columns, the home page offer is reduced to a narrow strip and the tables stick out of the screen. In the next module, Responsive Web Design, you'll start with the lesson Introduction to Responsive Design and learn how to make The Blue Cup adapt to any screen, from a phone to the widest monitor.

HTML Course

Module 1: Introduction to HTML

Module 2: Text Formatting in HTML

Module 3: Links and Media in HTML

Module 4: Tables in HTML

Module 5: Forms in HTML

Module 6: HTML5 Semantic Elements

Module 7: Advanced HTML Techniques

Module 8: Integrating HTML and CSS

Module 9: Responsive Web Design

Module 10: Best Practices and Accessibility

Module 11: Project: Building a Complete Website

© Copyright 2026. All rights reserved