I want to scale an image proportionally to cover the width and height of the browser window so that the user only has to scroll either to the side or down to see the entire image, regardless of the dimensions of the image and the browser. I have used min-width: 100vw and min-height: 100vh. The code works ok as long as the browser’s window is larger than the image’s pixel dimensions. How do I make it work on larger images?
Drawing of what I want
CSS
html, body {
width: 100%;
margin: 0;
padding: 0;
}
.full-plus {
width: calc(100vw - 20px);
height: calc(100vh - 20px);
background-color: red;
}
.full-plus img {
min-width: calc(100vw - 40px);
min-height: calc(100vh - 40px);
}
HTML
<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 the aspect-ratios.
Working Example:
const myDiv = document.querySelector('div.full-plus');
const resizeDiv = () => {
if (window.innerWidth / window.innerHeight) {
myDiv.style.setProperty('width', 'auto');
} else {
myDiv.style.setProperty('height', 'auto');
}
}
window.addEventListener('resize', resizeDiv);
resizeDiv();
body {
margin: 0;
}
div.full-plus {
position: fixed;
inset: 0;
width: 100vmin;
height: 100vmin;
background-image: url('https://www.w3schools.com/w3css/img_lights.jpg');
background-size: contain;
background-repeat: no-repeat;
}
<div class="full-plus"></div>
2