Centre anything

Centre a card in a large box, and stack the content of the card.

What to build

Two flex containers.

Requirements

  • .stage has a height of 200px, and centres .card both horizontally and vertically using flexbox.
  • .card is also a flex container, in a column direction, with a gap of 8px.
  • The two items in .card are aligned to the centre horizontally.

Constraints

Do not use margins, position or text-align.

Example

With flex-direction: column, align-items handles the horizontal direction.

Why it works

Changing the direction swaps the axes, so the same two properties control different directions.

Hints

Hint 1

A box needs a height for vertical centring to be visible.

Hint 2

In a column, justify-content works vertically.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Centre</title>
  <style>
    .stage {
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .card {
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: center;
    }
  </style>
</head>
<body>
  <div class="stage">
    <div class="card">
      <strong>Rina</strong>
      <span>Student</span>
    </div>
  </div>
</body>
</html>

Lesson: Flexbox: laying things out in a line →