CSS
Responsive N-Column Layout with Flexbox and Gap
Build flexible, multi-column layouts that wrap responsively on smaller screens using CSS Flexbox with `flex-wrap` and the `gap` property for consistent spacing.
.column-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
gap: 20px; /* Space between items */
padding: 20px;
background-color: #f8f8f8;
}
.column-item {
flex: 1 1 calc(33.333% - 20px); /* Approx 3 columns, adjusts for gap */
min-width: 280px; /* Minimum width before wrapping */
background-color: #fff;
border: 1px solid #eee;
padding: 15px;
box-sizing: border-box; /* Include padding/border in width calculation */
text-align: center;
}
/* For 2 columns on medium screens and 1 on small */
@media (max-width: 900px) {
.column-item {
flex: 1 1 calc(50% - 20px);
}
}
@media (max-width: 600px) {
.column-item {
flex: 1 1 100%;
}
}
How it works: This snippet creates a responsive N-column layout using Flexbox. The `display: flex` and `flex-wrap: wrap` properties enable items to flow onto new lines as space decreases. `gap` provides consistent spacing between items. The `flex: 1 1 calc(33.333% - 20px)` property on `column-item` allows items to grow (`1`), shrink (`1`), and defines a base width that aims for three columns while accounting for the `gap`. Media queries are included to demonstrate how to adjust column counts for different screen sizes, providing a highly adaptive layout.