Search code examples
csssasspositionaspect-ratioviewport-units

Size element proportionally to viewport


I would like to size an hmtl div element proportionally to viewport's size.

This element would be positioned into a dynamically sized container so it's not possible to use viewport units both for element's width and height.

I'm trying as far as possible to do this in pure CSS/SASS, I tried to use the aspect-ratio property but can't manage to make it work

.element {
 width: 80%; /*80% of container width*/
 aspect-ratio: calc(100vw/100vh);
}

Solution

  • Can't be done without JavaScript.

    In your case calc(100vw/100vh) is an invalid expression. Docs here.

    Using JavaScript:

    const updateRatios = () => {
      ;[...document.querySelectorAll(".viewport-ratio")].forEach((el) => {
        const { innerHeight, innerWidth } = window
        el.style.aspectRatio = innerWidth / innerHeight
      })
    }
    
    updateRatios()
    window.addEventListener("resize", updateRatios)
    .viewport-ratio {
      width: 50%;
      border: 1px solid red;
    }
    <div class="viewport-ratio"></div>
    Notes:

    • if not obvious, the CSS is not part of the solution, it was only added to make the solution visible without needing inspection.
    • any .viewport-ratio element added to DOM after script has run won't have the ratio until the updateRatios runs again (or window is resized).