Mặc định flex items nằm trên 1 dòng (flex-wrap: nowrap). Dùng flex-wrap: wrap để cho phép xuống hàng khi không đủ chỗ.
Ví dụ mã nguồn
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.container {
height: 300px;
display: flex;
width: 300px;
border: 2px solid red;
flex-wrap: wrap; /* Then chốt: cho phép xuống hàng */
}
div {
width: 150px;
height: 100px;
color: white;
text-align: center;
font-size: 20px;
display: flex;
align-items: center;
justify-content: center;
}
.first { background-color: rgb(55, 0, 255); }
.second { background-color: red; }
.third { background-color: rgb(140, 0, 255); }
</style>
</head>
<body>
<h1>Flex wrap example</h1>
<div class="container">
<div class="first">First Div</div>
<div class="second">Second Div</div>
<div class="third">Third Div</div>
</div>
</body>
</html>
Giá trị flex-wrap
| Giá trị | Mô tả |
|---|---|
| nowrap (mặc định) | Tất cả items trên 1 dòng, co lại nếu cần (overflow) |
| wrap | Items xuống hàng khi không đủ chỗ, thứ tự trái→phải, trên→dưới |
| wrap-reverse | Items xuống hàng, thứ tự trái→phải, dưới→trên (ngược cross axis) |
Shorthand: flex-flow
/* flex-flow = flex-direction + flex-wrap */
.container {
flex-flow: row wrap; /* Mặc định: row nowrap */
flex-flow: column wrap; /* Cột, xuống hàng ngang */
flex-flow: row-reverse wrap-reverse;
}
Kết hợp với gap & alignment
.container {
display: flex;
flex-wrap: wrap;
gap: 20px; /* Khoảng cách giữa items */
justify-content: center; /* Căn ngang: flex-start | center | flex-end | space-between | space-around | space-evenly */
align-content: flex-start; /* Căn dọc các hàng: flex-start | center | flex-end | space-between | space-around | stretch */
}
Ví dụ thực tế: Responsive Card Grid
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 24px;
}
.card {
flex: 1 1 300px; /* Tối thiểu 300px, tự co giãn, tự xuống hàng */
max-width: 400px;
}
Không cần media query! Grid tự responsive dựa trên container width.