user1263513
user1263513

Reputation: 91

Stretch image to viewport maintaining aspect ratio

Current setup:

HTML:

<html>
    <head>
        <meta charset="UTF-8" />
        <title>Fullscreen image</title>
    </head>
    <body>
        <img src="https://cdn.discordapp.com/attachments/187205892989648897/251689220819648513/e448455be034a36f6e09b46e671bdfd1.png" alt="Loading..." id="slide" />
    </body>
</html>

CSS:

* {
  margin: 0;
  padding: 0;
  border: 0;
}

html, body {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

#slide {
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

Demo of how I want things to look like: https://jsfiddle.net/fu3bL2Lx/1/

When you stretch and resize your browser, the image will still stay dead centered vertically and horizontally, while also fitting inside the viewport, keeping its aspect ratio.

The problem here is, when I click on the white space around the image, I still get the alert triggered that was bound to the img

I'm pretty sure this could be solved with flexbox if not with just regular unset display value, but I'm not very knowledgeable of it.

Upvotes: 1

Views: 2157

Answers (1)

roberrrt-s
roberrrt-s

Reputation: 8210

It's because your image is still occupying 100% of the viewport.

  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;

You actual image stays normal because of the object-fit property, MDN:

The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

Containing means:

The replaced content is sized to maintain its aspect ratio while fitting within the element’s content box: its concrete object size is resolved as a contain constraint against the element’s used width and height.

This is the reason you can click on the whitespace around the image.

Upvotes: 2

Related Questions