I have a perfectly square DIV - 500 x 500px.

I am going to be displaying images of unknown size in that DIV... some of the images are horizontal and some are vertical; some are larger than 500px tall or wide, some are smaller than 500px tall or wide. I don't control the image size.

How can I have any image I place in the DIV be expanded or reduced to best fill the box? My goal is that one axis of the image is always 500px, and the other axis is resized to fit. (This means that if the image is not perfectly square, there will always be blank space on either side of the image for vertical images, or above and below the image for horizontal images. That's ok.)

I know I can use JS or something server-side to do some math on the image sizes and compute new dimensions on the fly that way, but I'm seeking a CSS-only solution. Can flexboxes accomplish this?