How do I resize an image while keeping the aspect ratio if my parent container size is unknown, and dynamic

I’m making an image gallery. While working on the feature that brings the image to the full size of the browser window I realized that I can’t specifically set the size of the parent element that the img belongs to so it won’t play nice / fit how I want it to fit. I generally use the below trick for making images resize nicely while keeping the aspect ratio, staying centered nicely and not flowing over it’s parent element.

.keep-img-ratio {
    max-width: 100%;
    max-height: 100%;
    margin: auto;
  }

How do you solve this in a situation where the parent element of the img will be the size of the window which is dynamic and make the auto margin work?