CSS
Dynamic Flexbox Item Distribution with `gap` and `flex-grow`
Create a responsive layout where flex items distribute dynamically, fill available space, and maintain consistent spacing using `gap` and `flex-grow` properties.
<div class="flex-wrapper">
<div class="flex-card">
<h3>Card Title 1</h3>
<p>Short content.</p>
</div>
<div class="flex-card">
<h3>Card Title 2</h3>
<p>This card has slightly longer content to demonstrate how flex-grow works with varying text.</p>
</div>
<div class="flex-card">
<h3>Card Title 3</h3>
<p>Another card.</p>
</div>
<div class="flex-card">
<h3>Card Title 4</h3>
<p>Last one, with some content here.</p>
</div>
</div>
<style>
.flex-wrapper {
display: flex;
flex-wrap: wrap; /* Allow items to wrap to the next line */
gap: 20px; /* Use gap for consistent spacing between items */
padding: 20px;
border: 1px solid #e0e0e0;
max-width: 1000px;
margin: 20px auto;
}
.flex-card {
/* flex-grow: 1; -> allows items to grow and fill available space */
/* flex-shrink: 1; -> allows items to shrink */
/* flex-basis: target width before growing/shrinking */
/* Example: Aim for 3 cards per row, accounting for gap */
/* Calculation: calc((100% - ((N-1) * gap)) / N) where N is target items per row */
flex: 1 1 calc((100% - (2 * 20px)) / 3);
min-width: 250px; /* Prevent cards from becoming too narrow */
background-color: #e0f7fa;
padding: 15px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
display: flex; /* Flexbox inside card for content layout */
flex-direction: column;
}
.flex-card h3 {
margin-top: 0;
color: #00796b;
}
.flex-card p {
flex-grow: 1; /* Allows paragraph to take remaining vertical space if card is a flex container */
line-height: 1.5;
}
</style>
How it works: This snippet demonstrates a flexible and responsive card layout using Flexbox, incorporating the `gap` property for consistent spacing and `flex-grow` for dynamic sizing. The `flex-wrap: wrap` allows items to flow to new lines. `gap: 20px` provides both row and column spacing efficiently. The `flex` shorthand property on `.flex-card` (specifically `flex-grow: 1` and a calculated `flex-basis`) enables cards to grow and fill available space while aiming for a desired number of items per row, such as three, and shrinking when space is limited, respecting a `min-width`. This creates a robust and adaptable component distribution.