Tabs are an essential UI component, often used to divide content into multiple sections on a single page. While JavaScript is commonly used to develop tabs, did you know you can create a fully functional tab component using just HTML and CSS? This article will guide you through the process of developing a tab component using only the <radio>
and <label>
tags.
Setting Up the HTML Structure
To begin with, we need to set up the HTML structure. We'll use radio inputs for each tab and labels to toggle between them. The content for each tab will be placed in a corresponding <div>
.
<div class="tabs">
<!-- Tab 1 -->
<input type="radio" name="tab" id="tab1" checked>
<label for="tab1">Tab 1</label>
<div class="tab-content" id="content1">
Content for Tab 1
</div>
<!-- Tab 2 -->
<input type="radio" name="tab" id="tab2">
<label for="tab2">Tab 2</label>
<div class="tab-content" id="content2">
Content for Tab 2
</div>
<!-- Add more tabs as needed... -->
</div>
Notice that all radio inputs have the same name
attribute. This ensures that only one tab can be active at a time.
Styling with CSS
Now, let's add some styles:
/* Hide the radio inputs */
.tabs input[type="radio"] {
display: none;
}
/* Style the labels (tabs) */
.tabs label {
cursor: pointer;
display: inline-block;
margin-right: .2rem;
padding: .5rem 1rem;
}
/* Style the content sections */
.tab-content {
display: none;
padding: 1rem;
}
/* Display content when a tab is selected */
.tabs input[type="radio"]:checked + label + .tab-content {
display: block;
}
The key trick here is the :checked
pseudo-class. When a radio input is checked, the adjacent label and .tab-content
will be affected by the styles we define.
Enhancing the Active Tab
To give users a visual cue about which tab is active, let's highlight the active tab:
.tabs input[type="radio"]:checked + label {
background-color: #ddd;
}
This will change the background color of the active tab and remove its bottom border, creating a seamless look with the content section.
Final Result
Conclusion
By leveraging the power of the <radio>
and <label>
tags, combined with the capabilities of CSS, we've created a functional and stylish tab component without any JavaScript. This approach is lightweight, accessible, and offers a great user experience. Feel free to enhance the styles further to fit the design needs of your project!
Top comments (1)
Nice article. Thanks for sharing!
I am attempting the same, but the radio inputs are in the tab content and the labels are separated in the
<nav>
. Why doesn't this work?CSS