Home > Mobile >  SvelteJS styling specific element in each block
SvelteJS styling specific element in each block

Time:04-14

Giving the example of svelte js tutorial about each blocks https://svelte.dev/tutorial/each-blocks how could I left align the first cat, right align the second one, left align the third one and so on if I had more elements.

CodePudding user response:

Since you have the index available inside the each loop, you can set a class using the class:directive based on the condition if the index is dividable by 2 or not (in your case not, since you described to align the uneven indexes to the right) >> REPL

<script>
    let cats = [
        { id: 'J---aiyznGQ', name: 'Keyboard Cat' },
        { id: 'z_AbfPXTKms', name: 'Maru' },
        { id: 'OUtn3pvWmpg', name: 'Henri The Existential Cat' }
    ];
</script>

<h1>The Famous Cats of YouTube</h1>

<ul>
    {#each cats as { id, name }, i}
        <li class:align-right="{i%2 !== 0}">
            <a target="_blank" href="https://www.youtube.com/watch?v={id}">
            {i   1}: {name}
        </a>
    </li>
    {/each}
</ul>

<style>
    .align-right {
        text-align: right;
    }
</style>
  • Related