- Pat McKenna
- January 8, 2016
- HTML / CSS
About the Code
Responsive equal height images with CSS
Wanna put a bunch of images in a row, and make them all the same height? Well, you can. Flexbox to the rescue!
More info: Link
It’s slightly trickier than I first hoped, though – you need to:
- Put all of your images inside a container div
display: flex;on the container div
- Wrap each image in a div
- Set the
flexproperty of each image’s wrapper div to the image’s aspect ratio (its width divided by its height)
And boom! You’re done!
The only real bummer is having to declare the aspect ratio for each image. Depending on your preference or authoring process, you could do it a few different ways:
- Declare the aspect ratio in your stylesheet, with a class name for each wrapper div (as I’ve done in this demo)
- Declare the aspect ratio inline, as a
styleattribute on each wrapper div
With the CSS methods, you do have a few options for specifying the aspect ratio:
- Work out the aspect ratio yourself and hard-code it into the CSS (as I’ve done in this demo)
- Use CSS’s
calc()to calculate the aspect ratio (e.g.
- Use a preprocessor to calculate the aspect ratio at build time
Add as many images as you like – their widths will just shrink until they all fit.
Use with discretion though – if you add too many, they’ll all be too small to see. You might want to switch to a different layout at smaller viewport sizes.
Remember to vendor prefix those flexbox properties!