I want to scale an image proportionally so that one dimension is 100% of the viewport and the other is larger than the viewport but leave it uncropped and instead add scroll bars in the larger direction. It needs to work for images with different aspect ratios and with different aspect ratios of the viewport.
See this drawing (black is viewport, gray is image)
I have tried setting min-width: 100vw and min-height: 100vh. This works when the viewport is larger than the image’s pixel dimensions but not when it is smaller. (The image in the code is 600x400px. Run code snippet in full page and drag the browser window smaller than 600px wide and 400px high to see that the scaling of the image then does not match the viewport.)
I have also tried background-image but then the image is cropped with no scroll bars.
Since the code almost works, there should be an easy fix or do I need to solve it some other way?
html {
width: 100%;
margin: 0;
}
.full-plus {
width: 100vw;
height: 100vh;
}
.full-plus img {
min-width: 100vw;
min-height: 100vh;
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="full-plus">
<img src="https://www.w3schools.com/w3css/img_lights.jpg" alt="">
</div>
</body>
</html>
7
It needs to work on images with different aspect ratios.
@AHaworth is right – you’ll need JS here to:
- inspect and compare the original dimensions of the image
- inspect and compare the dimensions of the viewport
Working Example:
(Toggle to Full Page to see the effect…)
const bgImage = document.querySelector('.bgImage');
const resizeDiv = () => {
const imageDimensions = {
width: bgImage.naturalWidth,
height: bgImage.naturalHeight
}
if ((imageDimensions.width / imageDimensions.height) < (window.innerWidth / window.innerHeight)) {
bgImage.style.setProperty('width', '100vw');
bgImage.style.setProperty('height', 'auto');
} else {
bgImage.style.setProperty('width', 'auto');
bgImage.style.setProperty('height', '100vh');
}
}
window.addEventListener('resize', resizeDiv);
resizeDiv();
body {
margin: 0;
}
.bgImage {
position: absolute;
top: 0;
left: 0;
display: block;
}
<div>
<img class="bgImage" src="https://www.w3schools.com/w3css/img_lights.jpg" alt="Northern Lights" />
</div>
5