After experimenting, I discovered a neat CSS trick that creates a sliding effect on images. While it's possible to achieve this with CSS alone, using JavaScript allows for more dynamic mouse movement detection.
Here's how I created an image panning effect:
Start by creating a container div and centering all the elements inside. Set the width of the container to twice the width of your image, assuming a 300px by 300px image size.
HTML:
<div class="container"></div>
CSS :
.container {
display: flex;
justify-content: center;
width: 600px;
height: 300px;
}
Inside the container, place your image along with two additional divs – one before and one after the image.
<div class="container">
<div class="left"></div>
<img src="yourimage.png" alt="">
<div class="right"></div>
</div>
Ensure that the two extra divs match the height of your image and have half its width, while also setting their position to relative.
.left,
.right {
height: 100%;
position:relative;
width: 150px;
}
To create the hovering effect, position the left div to hover over the left side of the image and the right div over the right side.
.left {
left: 150px;
}
.right {
right: 150px;
}
On hover, add padding to both divs in opposite directions to move the image accordingly.
.right:hover {
padding-right: 50px;
}
.left:hover {
padding-left: 50px;
}
Since the container centers all elements, any padding added to one div will affect the positioning of other elements within the container.
View the interactive demo here: https://jsfiddle.net/L5c6xyLh/1/