• 2020-02-01

    Image aspect ratio before load

    Comments

    Start a discussion

    Before an image is loaded, the browser does not the aspect ratio of that image, so it jumps around. To fix it we can use the padding trick.

    Resize the content with the handle to see that the aspect ratio is still there.

    I've added broken images to simulate a before image load state.

    HTML

    <figure>
      <div class="fit-4-3">
        <img src="emulate-image-not-yet-loaded">
      </div>
    </figure>

    CSS

    figure {
      background: #ddd;
      width: 100px;
    }
    
    img {
      position: absolute;
      top: 0;
      left: 0;
    }
    
    .fit-4-3 {
      padding-bottom: 75%;
      position: relative;
    }

    To get the correct value in the padding you can use this tool: https://danieljones.design/css-aspect-ratio-calculator/

    Sources