Ricky Ricky - 4 months ago 66
CSS Question

Panning an image directionally based on mouse position with CSS

Okay, so its possible to get an image to pan to the left or the right etc with CSS3. For example:


<img src="pic.png" class="pan">


.pan:hover {
margin-right: -50px;

Thats kind of how it works.
Yet i would like to be able to get the image to pan in the direction the mouse moves over the image. Is this possible in CSS?
Otherwise i will have to resort to javascript and im not very familiar with that yet.


You made me wanna try this in CSS and actually you can do some trick to make it in work in some way, but it's definitly better with js where you can detect your mouse move.

Anyway that's how I made something that pan on each side.

create one container and center all div inside it, then give it twice the width of your image. Let's say your image is 300px width and 300 height.


<div class="container"></div>


.container {
    display: flex;
    justify-content: center;
    width: 600px;
    height: 300px;

In this container put your image and put one div before and one after it.

<div class="container">
    <div class="left"></div>
    <img src="yourimage.png" alt="">
    <div class="right"></div>

The two divs must have the same height as your image and half the width of it and you must give them a relative position.

.right {
    height: 100%;
    width: 150px;

Now we want to put those two divs on top of the image to trigger hover.

.left {
    left: 150px;

.right {
    right: 150px;

And now since they are on top of the image, we just have to add a padding (right to right and left to left) on hover to move the image.

.right:hover {
    padding-right: 50px;

.left:hover {
    padding-left: 50px;

Since the container center all divs, if one div has a padding, it move all the other div in this direction.

see fiddle: https://jsfiddle.net/L5c6xyLh/1/