Next.js Discord

Discord Forum

How to create global CSS variable using NextJSv13 ?

Unanswered
Egyptian Mau posted this in #help-forum
Open in Discord
Egyptian MauOP
Hello.
The title is self explanatory. We can't use :root since the selector is not pure so how can I create global CSS variables?
I'm a beginner with front-end development, sorry if the question sounds stupid but I can't find any answer on the web.

26 Replies

Why can't you make a CSS file and use root? (And import the file because it's nextjs)
For me, anything in that case file gets bundled into the outputed CSS (including root)
Egyptian MauOP
Hello @riský
Having this code:
:root {
    --default-font: Helvitica, sans-serif;
}

Produce this error: Syntax error: Selector ":root" is not pure (pure selectors must contain at least one local class or id)
That's why I'm confused about global CSS variable
what is your file name and how are you importing it?
actually, i just realised that i am using postcss (with tailwind) and i needed to do:
@layer base {
  :root {
      --var: value
  }
}
Egyptian MauOP
The pure CSS equivalent is actually my code, so do I need to use anything other than pure CSS?
well if you don't use postcss (which tailwind uses), you should beable to use root here: https://github.com/vercel/next.js/blob/canary/packages/create-next-app/templates/app/ts/app/globals.css
Egyptian MauOP
Yea, weirdly it doesn't work.
I took the code from here: https://github.com/vercel/next.js/blob/canary/examples/markdoc/pages/_app.tsx
Which include the globals.css file. Everything is the same but I get the same error
and just checking that you don't have postcss in yout package.json and postcss.config.js
Egyptian MauOP
Nop
  "dependencies": {
    "next": "13.5.4",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "@types/node": "20.8.3",
    "@types/react": "18.2.25",
    "@types/react-dom": "^18",
    "eslint": "^8",
    "eslint-config-next": "13.5.4",
    "typescript": "5.2.2"
  }
`
Egyptian MauOP
Yes
o.O
Egyptian MauOP
I started like yesterday and I'm kinda new so I don't have any fancy stuff here
yeah that makes sense
i am just a bit confused about this error now...
wait, you are using app dir
try using pages dir (like example) or remove _app.tsx (and move some of the code to layout)
Egyptian MauOP
Mhhh, still same thing. I'm doing something wrong ig.
In the layout file, I've a component called "Navbar" that include a styles CSS file that includes the the global CSS file. Does that sounds right to you?
Lol, that was the problem. The CSS file that include the global one produced the error.
What's the difference between the router app and pages? I've read the documentation and still can't figure out the main differences
I mean I didn't think that CSS was going to be that diferent between each other...
But going back to pages dir fixed it?
Egyptian MauOP
Removing the import inside the CSS fixed it
@import url("../../pages/globals.css");
Ohh ok