CodeBlanks Logo Icon CodeBlanks

Challenge - Flexbox gallery

CSS course · Intermediate · Lesson 94/98

Build a responsive photo gallery with flexbox.

Gallery skeleton with flexbox

In a photo gallery, cards line up horizontally and wrap to the next row on narrow screens. Flexbox is the cleanest way to build it. The .gallery container gets display: flex; with flex-wrap: wrap cards wrap when they no longer fit.

gap keeps a fixed space between cards, replacing margins. justify-content distributes leftover horizontal space: center packs them, space-between spreads them to the edges. align-items sets the vertical alignment. These four declarations form a flexible, readable gallery.

Exercise Complete the gallery

Complete the CSS below. The .gallery container should be flex, cards should wrap to the next line when narrow, and the gap between cards should be 1rem. Cards should be centered on the main axis. The .card should grow to fill leftover space and have a basis of 200px.

Show example solution
/* gallery container */
.gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  justify-content: center;
}

/* card */
.card {
  flex: 1 1 200px;
}

Test yourself

  1. Write the flex-wrap value

    .gallery {
      display: flex;
      flex-wrap: ____;
      gap: 1rem;
    }
    Show answer
    .gallery {
      display: flex;
      flex-wrap: wrap;
      gap: 1rem;
    }
  2. Match each flexbox property to its role

    flex-wrap
    Wraps cards when width narrows
    gap
    Fixed space between cards
    justify-content
    Distribution on main axis
    align-items
    Alignment on cross axis
    display: flex
    Makes the container flexible
  3. Which value makes cards drop to the next line on a narrow screen?

    .gallery {
      display: flex;
      flex-wrap: ???;
      gap: 1rem;
    }
    • nowrap
    • wrap
    • column
    • space-between
    Show answer

    wrap — Correct. wrap moves overflowing cards to the next line.

All lessons in Intermediate