Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Wrap the flex items with CSS
The CSS flex-wrap property controls whether flex items are forced onto a single line or can wrap onto multiple lines within a flex container. By default, flex items try to fit on one line, but wrapping allows them to break onto new lines when there isn't enough space.
Syntax
selector {
flex-wrap: value;
}
Possible Values
| Value | Description |
|---|---|
nowrap |
Default. Items are laid out in a single line |
wrap |
Items wrap onto multiple lines if needed |
wrap-reverse |
Items wrap onto multiple lines in reverse order |
Example: Basic Flex Wrap
The following example demonstrates how flex items wrap when there isn't enough space −
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
background-color: #D7BDE2;
flex-wrap: wrap;
width: 400px;
padding: 10px;
}
.mycontainer > div {
background-color: white;
text-align: center;
line-height: 40px;
font-size: 25px;
width: 100px;
margin: 5px;
border: 2px solid #8E44AD;
}
</style>
</head>
<body>
<h1>Quiz</h1>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
<div>Q5</div>
<div>Q6</div>
<div>Q7</div>
<div>Q8</div>
<div>Q9</div>
</div>
</body>
</html>
A purple container with white quiz boxes (Q1-Q9) that wrap onto multiple lines when they exceed the container width. The boxes are arranged in rows with proper spacing and borders.
Example: Comparing No-Wrap vs Wrap
This example shows the difference between flex-wrap: nowrap and flex-wrap: wrap −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
background-color: #E8F8F5;
width: 300px;
margin: 20px 0;
padding: 10px;
border: 2px solid #1ABC9C;
}
.nowrap {
flex-wrap: nowrap;
}
.wrap {
flex-wrap: wrap;
}
.item {
background-color: #1ABC9C;
color: white;
padding: 10px;
margin: 5px;
width: 80px;
text-align: center;
}
</style>
</head>
<body>
<h3>No Wrap (default):</h3>
<div class="container nowrap">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
</div>
<h3>With Wrap:</h3>
<div class="container wrap">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
</div>
</body>
</html>
Two containers are displayed: The first shows items squeezed into one line (no-wrap), while the second shows items wrapping to a new line when they exceed the container width (wrap).
Conclusion
The flex-wrap property is essential for responsive layouts, allowing flex items to wrap naturally instead of being forced into a single line. Use wrap for flexible layouts that adapt to different screen sizes.
Advertisements
