My issue:
Two identical images, both have a width and height specified in percent, yet the second image is taller and technically even wider.
In the code that I provided below, you can see a gray image (image 1) which is as tall as it should be. The colored image (image 2) is too tall and even too wide.
Move the slider and the red colored image container will show just below the gray image.
My code:
/* Moving slider updates img2 width percent */
function updateSliderInput(event) {
var widthPercent = 100 - (event.target.value * 0.1);
document.getElementById("img2").style.width = widthPercent + "%";
}
/* Adding an event listener to the slider */
document.querySelector("input[type='range']").addEventListener("input", updateSliderInput);
/* Initial setup, set comparison image initial width */
function initialSetup() {
var widthPercent = 100 - (document.querySelector("input[type='range']").value * 0.1);
document.getElementById("img2").style.width = widthPercent + "%";
}
initialSetup();
/* Main container, centered */
#container {
width: 50%;
margin: 0 auto;
background-color: #c7c7c7;
}
/* Images container */
#imageComparison {
position: relative;
background-color: rgb(150, 50, 50);
}
/* Grayscaling first image and setting width */
#img1 {
width: 100%;
filter: grayscale(100%);
}
/* Second image only */
#img2 {
position: absolute;
top: 0;
right: 0;
height: 100%;
object-fit: cover;
object-position: 100% 0;
}
.fix { height: calc(100% - 4px)!important; }
/* Range slider */
input[type="range"] {
width: 100%;
margin: 0;
}
<div id="container">
<div id="imageComparison">
<img src="https://fastly.picsum.photos/id/1013/300/200.jpg?hmac=OsBpo9MAg85j7O6gHzshfVJT3uWhz7-GW1piDibAqPA" id="img1">
<img src="https://fastly.picsum.photos/id/1013/300/200.jpg?hmac=OsBpo9MAg85j7O6gHzshfVJT3uWhz7-GW1piDibAqPA" id="img2">
</div>
<div id="imageControls">
<input type="range" min="0" max="1000">
<input type="checkbox" onclick="document.getElementById('img2').classList.toggle('fix');">
Apply temporary -4px fix
</div>
</div>
Possible temporary solution:
By changing #img2
> height: 100%;
to height: calc(100% - 4px);
, the image fits perfectly again. Is this a valid solution or is there a better fix for this? Why is it exactly 4 pixels, no matter what width?
Also, on my actual project, it's 8 pixels, not just 4, so from where do these pesky pixels come from?