John Hannah
John Hannah

Reputation: 33

Svelte global styles not working as expected

So I have a Svelte component that looks like this:

<div id="app">
  <h1>Page Title</h1>
  <p>Some text</p>
  <div><p>Some more text</p></div>
</div>


<style>
  div :global(p) {
    color: red;
  }
</style>

My expectation is that the p tags should be red, but that's not what's happening. I'm using webpack to build the app and the relevant config for Svelte is:

{
  test: /\.html$/,
  exclude: /node_modules/,
  use: 'svelte-loader'
}

The styles that are generated are:

    div.svelte-f5mkpg :global(p),
   .svelte-f5mkpg div :global(p){color:red}

I'm using Svelte 1.59.0 and svelte-loader 2.5.1. Any idea what's wrong here? I also see this behavior in the default Sapper app. The global CSS is actually in a global.css file and the :global styles don't seem to take.

Upvotes: 3

Views: 5728

Answers (1)

Rich Harris
Rich Harris

Reputation: 29605

In order to use the :global(...) modifier, you need to explicitly prevent CSS cascading:

{
  test: /\.html$/,
  exclude: /node_modules/,
  use: {
    loader: 'svelte-loader',
    options: {
      cascade: false
    }
  }
}

In version 2 (coming soon, hopefully) cascading will always be prevented, but it was necessary to put it behind an option until then to prevent a breaking change.

The compiler could warn on :global(...) if options.cascade !== false — I've opened an issue.

Upvotes: 6

Related Questions