0
0
CSSmarkup~5 mins

Flex wrap in CSS

Choose your learning style9 modes available
Introduction

Flex wrap helps items in a container move to the next line when there is not enough space. This keeps your layout neat and readable.

When you want items in a row to wrap to the next line on small screens.
When you have a list of buttons or images that should not shrink too small.
When you want a flexible grid that adjusts to different screen sizes.
When you want to avoid horizontal scrolling caused by too many items in one line.
Syntax
CSS
flex-wrap: nowrap | wrap | wrap-reverse;
nowrap means all items stay in one line (default).
wrap lets items move to the next line if needed.
wrap-reverse wraps items but in reverse order vertically.
Examples
All items stay in one line, even if they overflow the container.
CSS
flex-wrap: nowrap;
Items move to the next line when they don't fit in one line.
CSS
flex-wrap: wrap;
Items wrap to the next line but the new line appears above the previous one.
CSS
flex-wrap: wrap-reverse;
Sample Program

This example shows a flex container with five items. The flex-wrap: wrap; property lets items move to the next line if they don't fit in the container's width. Try resizing the browser window to see the wrapping effect.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Flex Wrap Example</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 1rem;
    }
    .container {
      display: flex;
      flex-wrap: wrap;
      gap: 1rem;
      background-color: #f0f0f0;
      padding: 1rem;
      border: 2px solid #ccc;
      max-width: 20rem;
    }
    .item {
      background-color: #4a90e2;
      color: white;
      padding: 1rem;
      flex: 0 0 8rem;
      text-align: center;
      border-radius: 0.5rem;
      user-select: none;
    }
  </style>
</head>
<body>
  <h1>Flex Wrap Example</h1>
  <p>Resize the browser window to see items wrap to the next line.</p>
  <section class="container" aria-label="Flex wrap container">
    <div class="item" tabindex="0">Item 1</div>
    <div class="item" tabindex="0">Item 2</div>
    <div class="item" tabindex="0">Item 3</div>
    <div class="item" tabindex="0">Item 4</div>
    <div class="item" tabindex="0">Item 5</div>
  </section>
</body>
</html>
OutputSuccess
Important Notes

Use flex-wrap with display: flex; on the container.

Combine flex-wrap with gap to add space between items.

Remember to test on different screen sizes to ensure good wrapping behavior.

Summary

Flex wrap controls if flex items stay in one line or wrap to new lines.

Use wrap to keep your layout neat on small screens.

Try resizing your browser to see how wrapping changes the layout.