Leet School

{module 4}

Layout with flexbox

Making it look right with CSS20 min read

What you will be able to do

  • Put elements side by side in a row, or in a column, with even gaps, using flexbox.
  • Build a navigation bar and a row of cards that wrap onto new lines when space runs out.
  • Find out from the developer tools why a layout is not what you expected.

Why it matters

Valencia Paella School teaches paella cooking in Valencia, Spain. Carmen Navarro, who runs it, had a page with three classes on it. Everything was in one long column: the name, then three menu links one under another, then each class as wide as the screen. On a laptop, a visitor had to scroll to see the second class, and had to remember a price to compare it with the next one.

Several visitors wrote to ask whether there was a vegetable class. It was on the page, further down. In this lesson the menu becomes one line, and the three classes sit side by side on a wide screen, where they can be compared at a glance.

The idea

Normal flow

Until now, the browser has placed boxes one under another, each as wide as the space it is in. Headings, paragraphs, lists and sections all do this. This is called normal flow. Layout is the part of CSS that changes it.

A flex container and its items

Flexbox is a way to place the children of one element along a line. You switch it on in the parent:

From styles.css
.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
}

display: flex makes the element a flex container. Its children, and only its direct children, become flex items. By default, the items sit in a row, side by side, from left to right.

gap is the space between items. It adds nothing at the outer edges, so the first item starts at the edge of the container.

A row or a column

The property flex-direction decides which way the line goes. Its default value is row. With column, the items stack one under another, and gap still puts even space between them:

From column.css
  flex-direction: column;

Wrapping

A row has only so much room. By default, the browser keeps all items on one line and squeezes them to fit. With flex-wrap: wrap, an item that does not fit moves to a new line, as words do in a paragraph.

How wide is each item?

Two properties on the items decide their size:

From styles.css
.card {
  box-sizing: border-box;
  flex-grow: 1;
  flex-basis: 15rem;

flex-basis is the width an item starts from, before the browser shares out the space. 15rem is 240 pixels.

flex-grow: 1 lets the item grow to fill the space left on its line. When every item has the same flex-grow, they share the space equally.

So the browser fits as many 240-pixel cards on a line as there is room for, then makes the cards on that line wider until the line is full. On a phone there is room for one, which grows to the full width. You never write a number of columns.

A container for the cards

The cards need a parent that holds only them. No element you know means "a group of cards", so this is the job of a div. A div is an element with no meaning at all. It exists to be styled, and it changes nothing for a screen reader.

A navigation bar

A menu is a list of links, so it is written as a list inside nav. Flexbox turns the list into one line:

From styles.css
.menu {
  display: flex;
  gap: 1.5rem;
  margin: 0;
  padding: 0;
  list-style: none;
}

list-style: none removes the bullets. A list has space on its left for bullets, and the browser also gives it margins, so this rule sets both to zero. It is still a list in the HTML, so a screen reader still says "list, three items".

Worked example

Make a folder called valencia-paella with this index.html:

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Valencia Paella School</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <header>
      <h1>Valencia Paella School</h1>
      <nav>
        <ul class="menu">
          <li><a href="#classes">Classes</a></li>
          <li><a href="#times">Times</a></li>
          <li><a href="mailto:hola@valenciapaella.example">Book</a></li>
        </ul>
      </nav>
    </header>
    <main>
      <h2 id="classes">Classes</h2>
      <div class="cards">
        <section class="card">
          <h3>Paella valenciana</h3>
          <p>Chicken, rabbit and green beans, cooked over a wood fire. $65 a person.</p>
        </section>
        <section class="card">
          <h3>Seafood paella</h3>
          <p>Prawns, mussels and squid, with a visit to the market first. $75 a person.</p>
        </section>
        <section class="card">
          <h3>Vegetable paella</h3>
          <p>Artichokes, peppers and beans from the farms around the city. $60 a person.</p>
        </section>
      </div>
      <h2 id="times">Times</h2>
      <p>Every class starts at 10:00 and ends with lunch at 14:00.</p>
    </main>
  </body>
</html>

The links #classes and #times jump to the element with that id on the same page. And this styles.css:

styles.css
/* Text #1f1f1f on white is 16.48 to 1, and red #9c2f0f on white is 7.43 to 1. */
body {
  max-width: 60rem;
  margin: 0 auto;
  padding: 0 1rem;
  background-color: #ffffff;
  color: #1f1f1f;
  font-family: Verdana, Arial, sans-serif;
  line-height: 1.5;
}

a {
  color: #9c2f0f;
}

header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

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

.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
}

.card {
  box-sizing: border-box;
  flex-grow: 1;
  flex-basis: 15rem;
  padding: 1rem;
  border: 2px solid #9c2f0f;
}

The header is a flex container too, with two items: the h1 and the nav. Two properties are new. justify-content: space-between puts the first item at the start of the line and the last at the end. The free space goes between them. align-items: center lines up their middles, so the short menu sits level with the middle of the tall heading.

Save both files and open the page in a wide window. The name is on the left and the menu on the right. The three classes sit side by side. Inspect the div, and the Computed tab confirms the settings:

Output
display: flex
flex-direction: row
flex-wrap: wrap
column-gap: 24px

gap is reported as column-gap, the space between items in a row. Now the width of each card, in a window 1280 pixels wide:

Output
card 1: 304px
card 2: 304px
card 3: 304px

The div is 960 pixels wide. Three cards of 240 and two gaps of 24 need 768, so all three fit on one line. The 192 pixels left over are shared, 64 each. In a window 768 pixels wide, the div is 736:

Output
card 1: 356px
card 2: 356px
card 3: 736px

Three cards would need 768, more than 736, so the third moved to a new line. Alone on its line, it grew to the full width. At the width of a phone, 390 pixels:

Output
card 1: 358px
card 2: 358px
card 3: 358px

One card on each line, as wide as the page. The menu has also moved under the name, because flex-wrap: wrap on the header let it. In Chrome and Edge, the Elements panel shows a small flex label next to each flex container. Click it, and the browser outlines the items and the gaps on the page.

Common mistakes

display: flex on an element with one child

From nav-flex.css
nav {
  display: flex;
  gap: 1.5rem;
}

The links are still one under another. Here is what the browser used:

Output
nav display: flex
ul display: block

The nav is a flex container, but its only child is the ul. A row of one item changes nothing, and the li elements inside the ul are still in normal flow. Flexbox places the direct children of the container. Put display: flex on the parent of the things you want in a row, which here is the ul.

Forgetting flex-wrap

Here is the .cards rule without flex-wrap: wrap, in a window 704 pixels wide:

Output
card 1: 208px
card 2: 208px
card 3: 208px

The cards did not wrap. The browser squeezed all three onto one line, below the 240 pixels you asked for. On a phone they are squeezed further, until the text no longer fits and the page scrolls sideways. With flex-wrap: wrap, the same window gives this:

Output
card 1: 324px
card 2: 324px
card 3: 672px

display: flex on the items

From card-flex.css
.card {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
Output
div display: block
card width: 960px

The div is an ordinary block, so each card fills the page, one under another. Each card has become a flex container, and its heading and paragraph sit side by side inside it. The rule is on the wrong element: display: flex goes on the container, not on the items.

Think it through

Carmen wants three things included in every class listed under the times: an apron, a recipe card and lunch. They should sit side by side on a laptop and be easy to read on a phone. Yuki, a learner, builds it.

Understand. Three short items in a row on a wide screen, wrapping on a narrow one, with equal widths on each line.

Break down. The HTML: a list, because they are a list. The container rule. The item rule. The width at which they wrap.

Plan. A ul with the class included, and three li elements with the class extra. The container gets display: flex, flex-wrap: wrap, gap: 1.5rem and no bullets. Each item gets flex-grow: 1 and a flex-basis. She first thinks of 10rem, 160 pixels. On a phone the page is 358 wide, and two items need 160 + 24 + 160 = 344, so two would fit on the first line and one would sit alone below. She prefers one per line on a phone, so she chooses 12rem: two then need 408.

Build. She writes the list and the two rules, with box-sizing: border-box, padding and a pale background on the items. She measures the text on that background: 15.17 to 1.

Test. At 1280 pixels, each item is 304 wide, all on one line. At 390, each is 358, one per line. For the odd case she tries 10rem after all: at 390, the first two items are 167 pixels each and the third is 358, as her sum predicted.

Reflect. The basis decides where the wrapping happens. A sum with the page width told her the answer before she reloaded.

At work

Saying what you will not do is as important as saying what you will do. A client fills every gap in your list with their own hopes. When you finish, the work you never meant to do looks like work you forgot.

Yuki's note to Carmen, before she started:

Carmen, this job covers the menu on one line and the three classes side by side on a laptop, one under another on a phone. I estimate 2 hours.

It does not include:

  • photos of the classes, which I would need from you
  • a booking form. The Book link opens an email, as today
  • changes to the text or the prices

Each of these is possible as a separate job, and I can estimate any of them.

Three short lines prevent the conversation that starts with "I thought you were also doing the photos". Carmen can still ask for them, and now she knows that it is a separate job.

Your tasks

Task 1: Build it and resize it

Build the page. Open the device toolbar from module 1 and set the width to 1280, then 768, then 390. At each width, inspect the cards in the Computed tab.

You are done when you have seen three cards on one line, then two and one, then one on each line, with the widths shown in the worked example.

Task 2: Find the wrapping point

Without the device toolbar, work out the narrowest window in which all three cards still fit on one line. The body has 16 pixels of padding on each side. Then check your answer with the device toolbar.

You are done when you have a number, worked out on paper, and the device toolbar shows three cards on one line at that width and two at one pixel less.

Task 3: Lay out your own page

Add a navigation bar to the top of your Kigali Threads page, with links to its sections, and put at least three of its parts side by side as cards. The parts must wrap onto separate lines at 390 pixels.

You are done when the menu is on one line on a laptop, the cards sit side by side, and at 390 pixels every card is on its own line with nothing past the right edge.

Recap

  • display: flex goes on the container. Only its direct children become flex items.
  • Items sit in a row by default. flex-direction: column stacks them, and gap spaces them either way.
  • Without flex-wrap: wrap, items are squeezed onto one line. With it, they move to a new line.
  • flex-basis is where an item starts and flex-grow: 1 lets items share the space left.
  • A navigation bar is a list of links in nav, made into a row with flexbox and list-style: none.

Go deeper