Make a clip-path inset a square on any viewport, in JS

Hello here is a codepen that shows my problem

I’m trying to make a JS calculation that changes the clip path inset of a div so that it shows a square.
There’s one constraint: the square width has to be 20vw

Here is an image that shows how it can look like on different viewports

I’m just looking for the right calculation based on viewport width/height/ratio
My brain is freezing 🙁 therefore the current calculation is wrong:

const clipPathInset = Math.abs(((0.2 * window.innerWidth) + (ratioDifference * window.innerWidth)) / 100)  

square.style.clipPath = `inset(${clipPathInset}px 40vw)`;

Any ideas?
I’ll then readjust the square width with media queries and/or resize event listener

Somebody commented but the comment isn’t there anymore
It was giving a solution that works

const squareWidth = 0.2 // equivalent to 20vw
const viewportRatio = window.innerWidth / window.innerHeight;
return window.innerWidth * (1 / viewportRatio - squareWidth) / 2;

I don’t understand why it works, but it works! Thank you

Leave a Comment