Setting top and left in percent instead of pixels

521 views Asked by At

I am using codrops image reveal hover effect on a project https://tympanus.net/codrops/2018/11/27/image-reveal-hover-effects/ and it is working fine (i am using effect 5).

I want to make a smalle change to this bit

            this.positionElement = (ev) => {
            const mousePos = getMousePos(ev);
            const docScrolls = {
                left : document.body.scrollLeft + document.documentElement.scrollLeft,
                top : document.body.scrollTop + document.documentElement.scrollTop
            };
            this.DOM.reveal.style.top = `${mousePos.y+20-docScrolls.top}px`;
            this.DOM.reveal.style.left = `${mousePos.x+20-docScrolls.left}px`;
        };

The bit where it sets the elements position, the last part, is set in px, is i possible to set that part in percent instead?, I want the image to be centred under the mouse cursor. I can do it by setting the value to minus half the image width and height, but thats not good if i want to make the image smaller on smaller screens. So a -50% value would be better.

2

There are 2 answers

0
Saar Davidson On BEST ANSWER

you should change just the css of the class hover-reveal so it would include the line:

transform: translate(-50%, -50%);

that way the image would be centered right under the mouse when it hovers the text because you moved it 50% of the height and length of the picture up and right.

0
SoroushOwji On

seems to me that what you need to change is not the pixel to a percentage but the anchor of the picture you want to reveal. which you can change via:

transform: translate( 0, -50%); 

I'm not sure the first input changes the x axis and second argument y or vise versa. but it's one way or another.

hope I've been some help!