[Next.js] Calculate vw size excluding scroll width

The vw based on the viewport is useful when you want to display the full screen width.

However, in browsers where scrolling is always displayed, such as Windows, the viewport including the scroll width is 100vw.
Therefore, set 100% when you want to display the full screen width excluding the scroll width.

Even so, there are situations where you still want to use 100vw.
In this case, we will calculate the vw size excluding the scroll width.

The version of Nextjs in this article is “13.5.4″.

目次

Initial setting of vw size

vw size styling.
–The vw variable is changed dynamically by JavaScript as described below.

import { createGlobalStyle } from "styled-components";

export const GlobalStyle = createGlobalStyle`
:root {
  --vw: 1vw;
}
`;

Load in _app.page.tsx so that it applies to all pages.

<GlobalStyle />

Implementation of hooks to change –vw.

Call it with hook.

Since 100vw includes the width of the scrollbars, store the viewport size excluding the scrollbars in the –vw variable and set the size excluding the scrollbars by doing calc(var(--vw) * 100).
The -vw should be recalculated each time resize is run.

import { useEffect } from "react";

export function useVw() {
  useEffect(() => {
    const setVw = () => {
      const vw = document.documentElement.clientWidth / 100;
      document.documentElement.style.setProperty("--vw", `${vw}px`);
    };

    setVw();
    window.addEventListener("resize", setVw);

    return () => {
      window.removeEventListener("resize", setVw);
    };
  }, []);
}

Defining –vw without scrollbars in CSS

–vw has a calculated value of 1vw in it, so by multiplying by 100, you can define CSS that takes the scroll width into account.

width: calc(var(--vw) * 100);

Summary

When using vw, the scrollbars are always visible in Windows, so when using vw, there is horizontal scrolling and I was wondering what to do… This is the solution.

よかったらシェアしてね!
目次