CodeBlanks Logo Icon CodeBlanks

Flex-wrap

CSS course · Intermediate · Lesson 5/98

Learn item wrapping with flex-wrap.

What is flex-wrap?

flex-wrap decides what happens when flex items no longer fit on a single line. Two core values: nowrap (the default) squeezes all items onto one line; in tight spaces they shrink or overflow. wrap drops the items that do not fit onto the next line.

For card galleries and tag clouds, wrap is almost mandatory.

The wrap value

When you pick wrap, items that do not fit the container's width drop automatically to the next line. As the screen shrinks, cards line up below each other instead of side by side; this is ideal for mobile summary lists.

The item sizes do not change; only the line count grows. With nowrap, items shrink to stay on a single line.

Building a card row

To build a card row, first write display: flex, then flex-wrap: wrap. As the container widens, cards line up side by side; as it narrows, they stack.

This is ideal for summary lists that show three columns on desktop and one on a phone. With nowrap, the cards would have been squashed on the phone screen.

Exercise Add wrapping to the card row

Add a .cards class selector. Inside, write display: flex and flex-wrap: wrap. The cards will then drop to the next line on a narrow screen.

Show example solution
/* add wrapping to the card row */
.cards {
  display: flex;
  flex-wrap: wrap;
}

Test yourself

  1. What does flex-wrap: nowrap do?

    .cards {
      display: flex;
      flex-wrap: nowrap;
    }
    • It keeps all items on a single line
    • It drops items that do not fit to the next line
    • It hides the items
    • It stacks items vertically
    Show answer

    It keeps all items on a single line — Correct. nowrap keeps all items on a single line; they shrink or overflow when there is no room.

  2. Let the cards wrap to a new line

    .cards {
      display: flex;
      flex-wrap: ____;
    }
    Show answer
    .cards {
      display: flex;
      flex-wrap: wrap;
    }
  3. Match the flex-wrap values

    wrap
    Drops overflow to the next line
    nowrap
    Keeps on a single line
    flex-wrap
    Wrapping declaration

All lessons in Intermediate