CSS
Responsive Column Layout with `flex-basis` and `calc()`
Implement a responsive column system where items wrap and adapt their width based on a minimum size and available space using `flex-basis` and `calc()` for dynamic layouts, without using `auto-fit` or `minmax`.
.flex-responsive-grid {
display: flex;
flex-wrap: wrap;
gap: 20px; /* Space between items */
padding: 10px;
width: 100%;
max-width: 960px;
margin: 0 auto;
border: 1px solid #ccc;
}
.flex-responsive-item {
flex-basis: calc(33.333% - 20px); /* Target 3 columns, adjust for gap */
flex-grow: 1; /* Allow items to grow to fill space */
flex-shrink: 1; /* Allow items to shrink if necessary */
min-width: 280px; /* Minimum width before wrapping */
background-color: lightblue;
border: 1px solid #ddd;
padding: 20px;
box-sizing: border-box;
text-align: center;
}
@media (max-width: 768px) {
.flex-responsive-item {
flex-basis: calc(50% - 20px); /* Target 2 columns on medium screens */
}
}
@media (max-width: 480px) {
.flex-responsive-item {
flex-basis: 100%; /* Full width on small screens */
}
}
/* HTML Structure */
<!--
<div class="flex-responsive-grid">
<div class="flex-responsive-item">Item 1</div>
<div class="flex-responsive-item">Item 2</div>
<div class="flex-responsive-item">Item 3</div>
<div class="flex-responsive-item">Item 4</div>
<div class="flex-responsive-item">Item 5</div>
<div class="flex-responsive-item">Item 6</div>
</div>
-->
How it works: This code snippet demonstrates a flexible and responsive column layout using `flex-basis` in conjunction with `calc()` and `flex-wrap`. The `flex-basis: calc(33.333% - 20px)` property attempts to make each item take up roughly one-third of the container's width, while accounting for a `20px` gap between items. `flex-grow: 1` ensures that items can expand to fill any remaining space in their row, and `min-width` prevents them from shrinking too much before wrapping. Media queries are then used to dynamically adjust `flex-basis` for different screen sizes, transitioning from a 3-column to a 2-column, and finally a single-column layout, providing a robust responsive grid without relying on CSS Grid's `auto-fit` or `minmax` features.