skip to Main Content

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.

Works but not responsive

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.

Unintended effect

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


  1. One way to make images responsive based on their container is with the object-fit CSS property. You can use it with object-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.asp

    Login or Signup to reply.
  2. Okay, I think I got your problem, its simple just change your CSS a bit,

    ✅ write this…

    .img-wrapper #full-img {
        background-image: url(https://images.unsplash.com/photo-1486870591958-9b9d0d1dda99?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80);
        background-repeat: no-repeat;
        background-position-x: fixed;
        background-position-y: center;
        z-index: 2;
    }
    

    ⛔️ instead of this…

    .img-wrapper #full-img {
        background-image: url(https://images.unsplash.com/photo-1486870591958-9b9d0d1dda99?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80);
        background-repeat: no-repeat;
        background-position: center;
        z-index: 2;
    }
    

    I hope it will help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search