What You'll Learn
You'll learn how to maintain consistent width-to-height proportions for flex items even as they grow, shrink, or wrap to different screen sizes.
Why Aspect Ratios Matter in Flexbox
An aspect ratio is the relationship between width and height (like 16:9 for widescreen or 1:1 for squares). When flex items grow or shrink, their dimensions change—but sometimes you want to keep the same shape.
Think of aspect ratios like picture frames: whether you have a tiny photo or a poster-sized print, a 4:3 frame always maintains that rectangular proportion. Flexbox doesn't automatically preserve aspect ratios when items resize, so you need to be intentional about it.
Combining Flexbox with Aspect Ratio Techniques
The most reliable approach uses padding-top percentage (a technique that works because percentage-based padding calculates based on the width of the container):
.flex-container {
display: flex;
gap: 1rem;
}
.flex-item {
flex: 1; /* Items grow equally */
min-width: 0; /* Prevents overflow */
}
.aspect-box {
position: relative;
width: 100%;
padding-top: 75%; /* 4:3 aspect ratio (height = 75% of width) */
background-color: lightblue;
}
As flex items grow or shrink with flex-grow and flex-shrink, the padding-top: 75% ensures the height always stays proportional to the changing width.
For a 1:1 square, use padding-top: 100%. For 16:9 widescreen, use padding-top: 56.25% (9÷16 = 0.5625).
When This Matters
Aspect ratios are crucial for image galleries, video thumbnails, card layouts, and any grid where visual consistency matters across different screen sizes.
Key Takeaway: Use percentage-based padding-top on an inner wrapper to maintain aspect ratios as flex items resize—Flexbox changes widths, but the padding percentage technique keeps heights proportional.