Next.js Discord

Discord Forum

Set css variable on page load

Answered
Large oak-apple gall posted this in #help-forum
Open in Discord
Large oak-apple gallOP
What is best way to set css variable when page loads or resizes?

Separate component with effect?
Inline <Script> with beforeInteractive strategy?
Inline with normal script?

I want to implement what is described in this article, so css variable needs to be set as soon as possible probably
https://liamhammett.com/how-to-create-full-width-containers-in-css#calculting-scrollbar-width
Answered by joulev
as soon as possible
then you need an inline <script>/<Script>
View full answer

15 Replies

Answer
Large oak-apple gallOP
Which is prefered in this situation?
both work, i don't have any preferences
Large oak-apple gallOP
Does strategy make difference in Script in this case?
@Large oak-apple gall Does strategy make difference in Script in this case?
i'll need to be honest with you, i have no idea. if you use <Script>, strategy="beforeInteractive" seems to be a must here to get it to run as soon as possible, but i don't know the difference between that and a regular <script>.

i guess it's just the placement of the <script> tag inside <head>? i encourage you to try it out and see what works better – the earlier the script tag is, the earlier it is run.
Large oak-apple gallOP
I see, thanks
American black bear
this has worked for me. I feel like it's simpler than using script.

export function RootLayout({children}: {children: React.ReactNode}) {

  return (
    <body
      style={
        {
          "--radius": radiusValue,
          "--font-body": bodyFont,
          "--font-heading": headingFont,
        } as CSSProperties
      }
    >
      {children}
    </body>
  )
}
@Large oak-apple gall Does it work at runtime? I need to calculate viewport width, so knowing it at build time will be hard
American black bear
I think it wont work for your purpose but you could probably use useLayoutEffect and js that injects the variable to the body
@American black bear I think it wont work for your purpose but you could probably use useLayoutEffect and js that injects the variable to the body
Large oak-apple gallOP
But isnt effect slow? It will be used in first screen. Will it cause layout shifts?
Large oak-apple gallOP
Actually not just first screen. It will affect whole page. If there is any layout shift, whole page will twitch
useLayoutEffect or anything react-y won’t work here because it needs to wait for the react runtime. That’s why I suggested <script>. There is a reason why anything built with no FOUC in mind, such as next-themes, must use <script>