0

I am using the each block similar to the code below. I have an array of items that is iterated through and then a button is create for all of the items.

<ul>
    {#each cats as { id, name }, i}
        <li><button target="_blank" href="https://www.youtube.com/watch?v={id}">
            {i + 1}: {name}
        </button></li>
    {/each}
</ul>

But I would like to stylize the buttons uniquely. For example I want the first button to be red and square, the next to be yellow and round, and the last normal. How would I go about adding that to the example above?

1 Answer 1

2

There are a couple ways I can see doing this:

Use the nth-child() selector to style each button differently:

li:nth-child(1) > button { color: red; }
li:nth-child(2) > button { color: green; }

Add a different class from an array based on the index

<script>
  const classes = ['green', 'red', 'yellow']
</script>
{#each item as item, i}
  <li class={classes[i]}>...</li>
{/each}

(here you could use the modulo operator if you want the classes to repeat)

A last way is to retrieve the classes from a function (this is very similar to the first one but can be more flexible)

<script>
  function getClasses(index) {
    return 'something here';
  }
</script>
{#each item as item, i}
  <li class={getClasses(i)}>...</li>
{/each}

If you don't want to use classes you can of course do a similar thing with styles instead

<script>
  function getStyle(index) {
    return 'something here';
  }
</script>
{#each item as item, i}
  <li style={getStyle(i)}>...</li>
{/each}
2
  • Using the first method, can I use javascript to pass in a value to the nth-child... So instead of: li:nth-child(1) => I can call x=5 in the script then pass that to the nth-child such as li:nth-child(x)
    – ITM007
    Commented Sep 2, 2021 at 20:04
  • no you can't, the only way you can communicate between the javascript and css in svelte is by adding it to a style attribute: style="color: red;" you could use css variables here though: style="--myvar: 122px" Commented Sep 3, 2021 at 6:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.