Let’s create a dynamic tab component using Alpine.js and Tailwind CSS, but first…
Tabs streamline user interfaces and enhance web experiences in numerous ways:
Tabs not only make content more accessible and appealing but also ensure a smoother and more engaging user experience.
The first step is to create the HTML structure for the tabs and panels. and this is how it looks like:
<div
x-data="{ activeTab: 0 }"
>
<!-- Tab List -->
<ul
role="tablist">
<!-- Tab 1 -->
<li>
<button
@click="activeTab = 0"
:aria-selected="activeTab === 0"
:class="{ '...': activeTab === 0 }"
class="..."
role="tab">
<!-- Icon and Title for Tab 1 -->
<span>My Account</span>
</button>
</li>
<!-- Tab 2 -->
<li>
<button
@click="activeTab = 1"
:aria-selected="activeTab === 1"
:class="{ '...': activeTab === 1 }"
class="..."
role="tab">
<span>Billing</span>
</button>
</li>
</ul>
<!-- Panels -->
<div
role="tabpanels">
<!-- Panel 1 -->
<section
x-show="activeTab === 0"
role="tabpanel">
<!-- Content for Panel 1 -->
</section>
<!-- Panel 2 -->
<section
x-show="activeTab === 1"
role="tabpanel">
<!-- Content for Panel 2 -->
</section>
</div>
</div>
x-data
attribute is used to define the initial state of the component, in this case, the active tab is set to 0.role
attribute is set to tablist
to indicate that the list of tabs is a tablist.role
attribute is set to tabpanels
to indicate that the list of panels is a tabpanels.role
attribute is set to tabpanel
to indicate that each panel is a tabpanel.aria-selected
attribute is set to true
for the active tab and false
for the inactive tabs.class
attribute is set to ...
to indicate that the class should be dynamically generated based on the active tab.@click
attribute is used to handle the click event on the tabs and update the active tab state.x-show
attribute is used to show or hide the corresponding panel based on the active tab.You can customize the CSS classes and styles to match your design preferences. In this example, we’re using Tailwind CSS classes to style the tabs and panels. Hope you enjoyed the tutorial and learned how to create a tab component with Tailwind CSS and Alpine.js.
"I bought a beautiful theme from Lexington a couple weeks ago. I didn't know Astro at the time, but Michael helped me get set up and really went above and beyond with his support. Now I'm happily redoing my site to look gorgeous with his template."
Stuart
Creator of saasydb.com
"Michael is one of the best designers on Twitter, would highly recommend his Lexington Themes if you want something in tailwind that doesn’t look the same as everyone else!"
Alex Hughes
letsloopin.com
Get lifetime access to every theme available today for $199 and own
them forever. Plus, new themes, lifetime updates, use on unlimited
projects and enjoy lifetime support.
No subscription required!
Lexington
Beautifully designed HTML, Astro.js and Tailwind themes! Save months of time and build your startup landing page in minutes.