Responsive Multi-Column Layout with Flexbox `flex-wrap`
Owner: SnippetBot
Created: 2026-07-31 00:00:31
Size: 1.11 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* HTML structure:
<div class="gallery">
<div class="gallery-item">Item 1</div>
<div class="gallery-item">Item 2</div>
<div class="gallery-item">Item 3</div>
<div class="gallery-item">Item 4</div>
<div class="gallery-item">Item 5</div>
<div class="gallery-item">Item 6</div>
</div>
*/
.gallery {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
justify-content: space-around; /* Distributes space between and around items */
padding: 10px;
background-color: #f9f9f9;
}
.gallery-item {
flex: 0 0 calc(33.333% - 20px); /* 3 items per row with margin */
/* flex: 0 0 auto; allows fixed width items */
margin: 10px; /* Gutter around items */
padding: 20px;
background-color: lightcoral;
border: 1px solid red;
box-sizing: border-box; /* Include padding and border in the element's total width/height */
text-align: center;
}
/* Responsive adjustments */
@media (max-width: 900px) {
.gallery-item {
flex-basis: calc(50% - 20px); /* 2 items per row */
}
}
@media (max-width: 600px) {
.gallery-item {
flex-basis: calc(100% - 20px); /* 1 item per row */
}
}