frank3stein
frank3stein

Reputation: 706

Svelte: Is there a way to make global css variables in scope of svelte components?

I have set my global.css file which I import in index.js

--root {
  --main-color: red;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

index.js

import "./global.css";
import App from "./App.svelte";

const app = new App({
  target: document.body
});

My webpack setup

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(html|svelte)$/,
        exclude: /node_modules/,
        use: {
          loader: "svelte-loader",
          options: {
            emitCss: true,
            hotReload: true
          }
        }
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: { loader: "style-loader", options: { sourceMap: true } },
          use: [
            { loader: "css-loader", options: { sourceMap: true } },
            {
              loader: "postcss-loader",
              options: {
                sourceMap: true,
                ident: "postcss",
                plugins: loader => [
                  require("postcss-import")({}),
                  require("postcss-preset-env")(),
                  require("cssnano")()
                ]
              }
            }
          ]
        })
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin(), new ExtractTextPlugin("styles.css")]
};


Works perfect for setting up global css for the entire app. But I am trying to use the --main-color in my svelte components. Is there a way to inject them down to all the components' css ?

Since I import global.css first, it should work as it emits a file with --root{} first then rest of the component styles.

Upvotes: 21

Views: 32983

Answers (2)

Ivan Afanasyev
Ivan Afanasyev

Reputation: 491

You can place global styles under /routes/index.svelte file, like the example below:

<style>
    :global(:root){
       --header-color: purple
    }
</style>

And simply use it anywhere like normally how you use CSS variables like so:

  h1 {
         color: var(--header-color);
  }

Upvotes: 38

frank3stein
frank3stein

Reputation: 706

I was busy with this, trying different webpack settings etc., seeing that the output css should work, I just could not find why it did not work. I wrote the post before trying for one last time, which wasted another hour. I finally found the error.

Instead of using :root{} I have mistyped it --root{}. I have posted it anyways, in case someone is stuck with the same mistake.

Upvotes: 12

Related Questions