Search code examples
cssanimationsveltesvelte-3

Svelte: doesn't work inline css animation


Doesn't work inline css animation like this:

<h1 class="test" style="animation: bg 2s linear infinite">Hello {name}!</h1>

<style>
.test { 
    background: yellow;
}

@keyframes bg {
    from {
      background: red;
    }
    to {
      background: green;
    }
  }
</style>

https://svelte.dev/repl/e32b72cb98cb4b78a47b1bcb1ecab9e9?version=3.53.1

But if delete style attribute

<h1 class="test">Hello {name}!</h1>

and add

.test 
    background: yellow;
    animation: bg 2s linear infinite;
}

It works! But I want to add animation as inline style.


Solution

  • Everything within a component style is scoped to the component by default and the inline style apparently is not recognized as referring to the defined @keyframes.

    Regular selectors can be made global using :global() around the selector but for @keyframes you would have to prefix the name with -global- (which is removed again on compilation).

    @keyframes -global-bg { ... }
    

    REPL

    Note that this really is defined as global then and any other component that defines global keyframes with the name bg will cause interference.