I’m making a reveal on mouse move effect on my site to have two divs with background images on top of each other. As the mouse moves, the width of the left one changes accordingly.
The problem is I want to center the background image regardless of the viewport width (I want it to be responsive). But when I set a background-position-x: center on the image, I get this unwanted effect of the left image being left behind instead of being aligned with the behind image.
Here is my code:
HTML
<div class="fox-wrapper">
<div id="full-fox"></div>
<div id="empty-fox"></div>
</div>
CSS
.fox-wrapper {
height: 100vh;
}
.fox-wrapper #full-fox, .fox-wrapper #empty-fox {
display: block;
position: absolute;
height: 100%;
width: 100%;
}
/* "left" (in front) image */
.fox-wrapper #full-fox {
background-image: url("../page-media/fox-dashed.png");
background-repeat: no-repeat;
background-size: cover;
background-position: center;
z-index: 2;
}
/* "right" (behind) image */
.fox-wrapper #empty-fox {
background: url("../page-media/bg.png");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
width: 100%;
}
JS
document.onmousemove = e => {
const fullFox = document.getElementById("full-fox");
let x = e.clientX;
let width = window.innerWidth;
let percent = 100 * x / width
fullFox.style.width = `${percent}%`;
}
Codepen demo:
https://codepen.io/davefoxxo/pen/ZEMrXEq
2
Answers
One way to make images responsive based on their container is with the
object-fit
CSS property. You can use it withobject-fit: cover;
to keep the aspect ratio of the image and fill the given dimension. The image will be clipped to fit. You can view a demo and more information here: https://www.w3schools.com/css/css3_object-fit.aspOkay, I think I got your problem, its simple just change your CSS a bit,
✅ write this…
⛔️ instead of this…
I hope it will help you.