Create equal height images with CSS

Create equal height images with CSS

See the Pen Responsive equal height images with CSS by Pat McKenna (@blimpage) on CodePen.

Author

  • Pat McKenna
  • January 8, 2016

Made with

  • 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

Dependency:

Responsive: Yes

It’s slightly trickier than I first hoped, though – you need to:

  1. Put all of your images inside a container div
  2. Set display: flex; on the container div
  3. Wrap each image in a div
  4. Set the flex property 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 style attribute on each wrapper div
  • Dynamically calculate the aspect ratio for each image using JavaScript

That last option is tempting; not needing JavaScript is nice, but needing to specify the aspect ratio for each and every image is a pain.

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. flex: calc(600/800);)
  • 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!

Maddy
12+ years of solution-driven experience, excelling in highly collaborative work environment, finding solutions to challenges and focused on customer satisfaction. Proven experience developing user-friendly web/mobile applications. Experience in applying DevOps automation integrating with Cloud solutions, following Agile principles.