skip to Main Content

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?

Edit: When I set img style to display: block; it will center horizontally, but not vertically.

2

Answers


  1. Chosen as BEST ANSWER

    I found that this answer mostly gives the behavior I'm looking for. Here

    I also reposted it below

    If anyone knows a better way then please share.


    To center it, you can use the technique shown here: Absolute centering.

    To make it as big as possible, give it max-width and max-height of 100%.

    To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use object-fit.

    .className {
        max-width: 100%;
        max-height: 100%;
        bottom: 0;
        left: 0;
        margin: auto;
        overflow: auto;
        position: fixed;
        right: 0;
        top: 0;
        -o-object-fit: contain;
        object-fit: contain;
    }
    
    <img src="https://i.imgur.com/HmezgW6.png" class="className" />
    
    <!-- Slider to control the image width, only to make demo clearer !-->
    <input type="range" min="10" max="2000" value="276" step="10" oninput="document.querySelector('img').style.width = (this.value +'px')" style="width: 90%; position: absolute; z-index: 2;" >
    

  2. Try this for full screen:

    .image-wrapper {
        width: 100%;
    }
    img {
        max-width: 100vw;
        max-height: 100vh;
    }
    

    Or this for a variable width:

    .image-wrapper {
        width: 500px;
    }
    img {
        width: 100%;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search