简体   繁体   中英

How to use CSS Global Variables?

first of all thank you so much for your time.

My doubt is simple, but i couldn't find a way to get it working.

So... basically i have a '/pages/_app.js' file:

import '../public/styles/global.css';

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

A global css file '/public/styles/global.css':

:root {
  --bg-color: #000;
}

A css module file '/public/styles/header.module.css':

.header {
  background-color: var(--bg-color);
}

And finally a home page '/pages/index.js'that uses the css class:

import React from 'react';
import headerStyle from '../public/styles/header.module.css';

export default function Home() {
  return <div className={headerStyle.header}>Test</div>;
}

I don't get an error but i didn't manage to refer to the global variables inside the css modules. Can you guys help me with what am i doing wrong?

If the pages/ directory exists under src/ then the path to the <Home> component should be /src/pages/ and the import for the headerStyle should be the following:

import headerStyle from "../../public/styles/header.module.css";

You just need to go up one more directory.

/*
 *  @filename /src/pages/index.jsx
 */
import React from "react";
import headerStyle from "../../public/styles/header.module.css";

const Home = () => {
  return <div className={headerStyle.header}>Test</div>;
};

export default Home;

Here is a CodeSandbox snippet to demonstrate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM