Svelte: dynamic CSS classes

- Posted in svelte - 1 comment

I might start writing some blog posts to keep up with learning Svelte. I wrote this one, more might follow, but I am not promising anything ;).

The first topic of today is :class.

Take a look at this code, we add a class of .blue when foo is true:

<script>
   var foo = true;
 </script>
 <style>
   .blue { color: blue; }
 </style>
 <h1 class="blue {foo ? 'foo': ''}">Hello world</h1>

This code works but it’s not very Svelte-ish.

In Svelte you can dynamically add a class based on, for example, whether a Javascript variable is true or false.

For example

<script>
  var foo = true;
</script>

<style>
  .red { color: red; }
</style>

<h1 class:red="{foo}">Hello world</h1>

Now, you can also combine a regular class with an “optional class”:

<script>
   var foo = true;
 </script>

 <style>
   .red { color: red; }
   .blue { color: blue; }
 </style>

 <h1 class="blue" class:red={foo}>Hello world</h1>

Here is a real life example of this in practice:

In App.svelte:

<script>
     import Button from './Button.svelte';
 </script>
 <Button>Hey</Button>
 <Button variant="primary">Hey</Button>
 <Button variant="success">Hey</Button>

In Button.svelte:

<script>
     export let variant = null;
 </script>
 <style>
     .button { padding: 0.5rem; }
     .primary { background: #748DD5; border-color: #748DD5; color: #FFF; }
     .success { background: #75D37E; border-color: #75D37E; color: #FFF; }
 </style>
 <button
   class="button"
   class:primary={variant==='primary'}
   class:success={variant==='success'}
 >
     <slot></slot>
 </button>

See this REPL for an example.

1 Comment

  • fun code; try this:

    .button { padding: 0.5rem; }
    .primary { background: #748DD5; border-color: #748DD5; color: #FFF; }
    .primary:active { background: dodgerblue; }
    .success { background: #75D37E; border-color: #75D37E; color: #FFF; }
    .success:active { background: lime; }

    then you can see the button clicks

Leave a Reply

Your email address will not be published. Required fields are marked *