DEV Community

Cover image for How to Create Tabs with Tailwind and Svelte
saim
saim

Posted on • Originally published at larainfo.com

How to Create Tabs with Tailwind and Svelte

In this section we will create tabs in svelte with tailwind css.

Install Tailwind CSS in Svelte with Typescript Using Vite

Tool Use

Tailwind CSS 3.x
Svelte

Example 1

svelte with tailwind css simple tabs.

<script>
  let openTab = 1;

  function toggleTabs(tabNumber) {
    openTab = tabNumber;
  }
</script>

<div class="flex flex-col items-center justify-center h-screen">
  <div class="flex">
    <div
      class="px-4 py-2 cursor-pointer {openTab === 1
        ? 'bg-blue-600 text-white'
        : 'bg-gray-200'}"
      on:click={() => toggleTabs(1)}
    >
      Tab 1
    </div>
    <div
      class="px-4 py-2 cursor-pointer {openTab === 2
        ? 'bg-blue-600 text-white'
        : 'bg-gray-200'}"
      on:click={() => toggleTabs(2)}
    >
      Tab 2
    </div>
    <div
      class="px-4 py-2 cursor-pointer {openTab === 3
        ? 'bg-blue-600 text-white'
        : 'bg-gray-200'}"
      on:click={() => toggleTabs(3)}
    >
      Tab 3
    </div>
  </div>
  {#if openTab === 1}
    <div>Content for Tab 1</div>
  {:else if openTab === 2}
    <div>Content for Tab 2</div>
  {:else}
    <div>Content for Tab 3</div>
  {/if}
</div>
Enter fullscreen mode Exit fullscreen mode

svelte with tailwind tabs


Example 2

svelte with tailwind css tabs using each loop.

<script>
  let tabs = [
    { title: "Tab 1", content: "Content for Tab 1" },
    { title: "Tab 2", content: "Content for Tab 2" },
    { title: "Tab 3", content: "Content for Tab 3" },
  ];

  let activeTab = tabs[0].title;

  function setActiveTab(tabTitle) {
    activeTab = tabTitle;
  }
</script>

<style>
  .active {
    background-color: blue;
    color: white;
  }
</style>

<div class="flex">
  {#each tabs as tab (tab.title)}
    <div 
      class="px-4 py-2 cursor-pointer {activeTab === tab.title ? 'active' : 'bg-gray-200'}" 
      on:click="{() => setActiveTab(tab.title)}"
    >
      {tab.title}
    </div>
  {/each}
</div>

{#each tabs as tab (tab.title)}
  {#if activeTab === tab.title}
    <div>{tab.content}</div>
  {/if}
{/each}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)