HTML Accordion - Radio Button Implementation

I need help with my accordion code,

My goal is to achieve the following functionality:

The Radio Button Method involves adding a hidden radio input and label tag to each accordion tab.

The concept is simple:

  • When a user selects a tab, they are essentially checking the radio button linked to that tab.
  • As the user clicks on the next tab, the next radio button is selected, and so on. This method allows only one tab to be open at a time.

I am seeking guidance on how to integrate this technique into my existing accordion code.

<!doctype html>

<html>
<head>
    <style>
        input {
            display: none;
        }

        label {
            display: block;    
            padding: 8px 22px;
            margin: 0 0 1px 0;
            cursor: pointer;
            background: #6AAB95;
            border-radius: 3px;
            color: #FFF;
            transition: ease .5s;
            position: relative; /* ADDING THIS IS REQUIRED */
        }

        label:hover {
            background: #4E8774;
        }

        label::after {
            content: '+';
            font-size: 22px;
            font-weight: bold;
            position: absolute;
            right: 10px;
            top: 2px;
        }

        input:checked + label::after {
            content: '-';
            right: 14px;
            top: 3px;
        }

        .content {
            background: #E2E5F6;
            padding: 10px 25px;
            border: 1px solid #A7A7A7;
            margin: 0 0 1px 0;
            border-radius: 3px;
        }

        input + label + .collapse {
            display: none;
        }

        input:checked + label + .collapse {
            display: block;
        }
    </style>
</head>

<body>
    <input type="checkbox" id="title1" />
    <label for="title1">Accordion 1</label>

    <div class="collapse">
        <p>Your content goes here inside this division with the class "content".</p>
    </div>

    <input type="checkbox" id="title2" />
    <label for="title2">Accordion 2</label>

    <div class="collapse">
        <p>Your content goes here inside this division with the class "content".</p>
    </div>
</body>
</html>

Answer №1

No modifications necessary on the CSS code (especially the part responsible for the accordion functionality), but some adjustments are required in the HTML markup.

To achieve the desired accordion behavior where only one tab can be open at a time, follow these steps:

  • Replace checkboxes with radio buttons (input[type="radio"]).
  • Ensure all radio buttons within the accordion have the same name attribute value (uniformly set the name attribute to accomplish the objective).

Take a look at this live demo:

/** The CSS remains unchanged, refer to the HTML section for necessary alterations */

input {
  display: none;
}

label {
  display: block;
  padding: 8px 22px;
  margin: 0 0 1px 0;
  cursor: pointer;
  background: #6AAB95;
  border-radius: 3px;
  color: #FFF;
  transition: ease .5s;
  position: relative;
  /* THIS ADDITION IS ESSENTIAL */
}

label:hover {
  background: #4E8774;
}

label::after {
  content: '+';
  font-size: 22px;
  font-weight: bold;
  position: absolute;
  right: 10px;
  top: 2px;
}

input:checked+label::after {
  content: '-';
  right: 14px;
  top: 3px;
}

.content {
  background: #E2E5F6;
  padding: 10px 25px;
  border: 1px solid #A7A7A7;
  margin: 0 0 1px 0;
  border-radius: 3px;
}

input+label+.collapse {
  display: none;
}

input:checked+label+.collapse {
  display: block;
}
<!-- Switched "type=checkbox" to "type=radio" -->
<!-- Assigned the same value to the "name" attribute for all radio buttons -->
<input type="radio" name="radio-btn" id="title1" />
<label for="title1">Accordion 1</label>
<div class="collapse">
  <p>Content goes here inside the division with class "content".</p>
</div>
<!-- Switched "type=checkbox" to "type=radio" -->
<!-- Assigned the same value to the "name" attribute for all radio buttons -->
<input type="radio" name="radio-btn" id="title2" />
<label for="title2">Accordion 2</label>
<div class="collapse">
  <p>Content goes here inside the division with class "content".</p>
</div>

NOTE: While the radio buttons method achieves the desired result, it may not allow you to close all accordion items after initial interaction (though you can start with closed accordions). Proceed with caution.

Answer №2

I stumbled upon a fantastic example utilizing Sass that perfectly aligns with your requirements: https://codepen.io/alvarotrigo/pen/dyJbqpd.

This particular example employs radio buttons, like the code snippet below:

 <input type="radio" id="title1" name="select"/>
. Since they share the same name attribute, only one can be selected at a time.

In the scenario you provided, checkboxes are utilized similar to this demonstration found on w3schools.com. With checkboxes, multiple selections can be made concurrently, which explains the current accordion behavior.

Below is a simplified version of the example converted into CSS:

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

.tab {
  overflow: hidden;
}
  
.tab-label {
    display: flex;
    justify-content: space-between;
    padding: 1em;
    background: #2c3e50;
    color: white;
    cursor: pointer;
}

.tab-content {
    max-height: 0;
    padding: 0 1em;
    color: #2c3e50;
    background: white;
}

input:checked ~ .tab-content {
    max-height: 100vh;
    padding: 1em;
}
<div class="tab">
  <input type="radio" id="rd1" name="rd">
  <label class="tab-label" for="rd1">Item 1</label>
  <div class="tab-content">Content</div>
</div>
<div class="tab">
  <input type="radio" id="rd2" name="rd">
  <label class="tab-label" for="rd2">Item 2</label>
  <div class="tab-content">Content</div>
</div>

I made slight adjustments to your code and introduced an additional div with overflow set to hidden:

/** no changes were made in the CSS section, refer to the HTML part for necessary modifications */

input {
  display: none;
}

label {
  display: block;
  padding: 8px 22px;
  margin: 0 0 1px 0;
  cursor: pointer;
  background: #6AAB95;
  border-radius: 3px;
  color: #FFF;
  transition: ease .5s;
  position: relative;
  /* ADDING THIS IS REQUIRED */
}

label:hover {
  background: #4E8774;
}

label::after {
  content: '+';
  font-size: 22px;
  font-weight: bold;
  position: absolute;
  right: 10px;
  top: 2px;
}

input:checked+label::after {
  content: '-';
  right: 14px;
  top: 3px;
}

.content {
  background: #E2E5F6;
  padding: 10px 25px;
  border: 1px solid #A7A7A7;
  margin: 0 0 1px 0;
  border-radius: 3px;
}

input+label+.collapse {
  display: none;
}

input:checked+label+.collapse {
  display: block;
}
<div class="tab">
  <input type="radio" id="title1" name="select"/>
  <label for="title1">Accordion 1</label>
  <div class="collapse">
      Your content goes here inside this division with the class "content".
  </div>
</div>
<div class="tab">
  <input type="radio" id="title2" name="select" />
  <label for="title2">Accordion 2</label>

  <div class="collapse">
      Your content goes here inside this division with the class "content".
  </div>    
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for ensuring that the footer remains at the bottom of the content and stays fixed at the bottom of the viewport

In my Django project, I am using Bootstrap 4.5 and I need the footer to be in one of two positions: 1- At the bottom of the content if the content is larger than the view height 2- At the bottom of the viewport if the content is smaller than the view hei ...

Reposition picture "overlays" additional HTML components

I am struggling with rotating an image by clicking on a button as the image overlaps the buttons. Can anyone provide guidance on how to achieve this without overlapping? For reference, here is my code and an example: here (http://jsfiddle.net/jj03b17n/5/) ...

Is there a way to adjust the transparency of specific text when clicking on a different div?

How can I display a line of text when the "Contact Us" button is clicked on a practice website, similar to this: https://i.sstatic.net/MgbYQ.png I have set the current opacity of the submit message to 0 so it is hidden, but is there a way to change its o ...

`Passing JavaScript variables through HTML anchor tags`

I am currently attempting to pass the id to the controller using this method: {{ route("admin.service.edit", '+val[0]+' )}} However, the '+val[0]+' is being interpreted as a string in the URL http://localhost:8000/admin/servi ...

Achieving www prefix enforcement for loading js file

I am facing an issue with the script on my website, which is built using OpenCart. The problem arises when accessing the site with a www prefix - the JavaScript file fails to load. However, when accessed without the www prefix (e.g. example.com), everyth ...

The div element is shifting as the page is being resized

When I increase the zoom level of my page to 110%, the div inside the larger one keeps getting bigger and eventually moves to a new line. Is there a way to stop it from shifting? If so, please provide guidance on how to fix this issue without criticizing m ...

Creating a CSS triangle that smoothly transitions between two different colors

Is it possible to create a triangle in CSS that smoothly transitions between two colors without relying on a hover state? .arrow-down { width: 0; height: 0; border-left: 20px solid transparent; border-right: 20px solid transparent; b ...

HTML various button designs - such as a cogwheel

I need a button on my Angular/Electron project that resembles a gear icon. I came across these resources: here and here. However, when I tried to implement them, they didn't work as expected. Currently, the button looks like this: <button class= ...

Discovering the selected row with jqueryIs there a way to locate

There is a table with rows and a button that allows you to select a row: <table id="mytable" class="table-striped"> <tbody> <tr id="1"><td>Test1</td></tr> <tr id="2"><td>Test2</td>& ...

Toggle div visibility with a click

Hello, I've created a mailbox with show/hide functionality on :hover. However, someone recently mentioned that this could be quite distracting for users. Since pure CSS doesn't allow me to achieve the same effect on :active, I'm wondering if ...

Utilizing Jquery cycle to overlay a div on top of a scrolling image

Hey there! I'm currently using the jquery.cycle.all.js plugin for my website. I've encountered an issue where I want to position a menu div on top of an image slider. The menu is in the correct location, but unfortunately, it's hidden benea ...

Update table content dynamically without the need to refresh the entire page while maintaining the original CSS

I have been encountering an issue with my ASP .NET code. I have spent hours researching but haven't found a solution that works for me. My problem is that when I click a button, the text inside a textbox should be added to a dropdown and update a tabl ...

Balanced row heights within a CSS grid

Using a basic grid framework like , I have a fixed number of rows. I'm wondering if there's a simple way to ensure that all rows have the same height without explicitly setting the height of the .row class as a percentage. This is how my row cla ...

Header with a list and an accompanying image using HTML and CSS

Struggling to incorporate a header featuring a list and a small logo in the top right corner of the page, seamlessly integrated with the header lines. The first image link reflects my desired result while the second image shows where I'm encountering ...

Exploration of HTML SVG map image tracking a specific route

Currently, I have an SVG file embedded in my HTML code. The SVG has a viewbox set to 500x500. Within this SVG, there is an Image element that is 2500x2500 in size, depicting a large map. Using Illustrator, I created a path that traces the roads on the ma ...

Arrange documents according to the final two characters

My method for collecting files from a folder involves using some Smarty code: {assign var=files value="uploads/Documenten/GPS-Tracks/*.html"|glob} {if count($files)} <ul> {foreach from=$files item='file'} {assign v ...

What is the best way to modify a variable in a nested element using ng-click in the parent element?

Review this code snippet: <section class="page-section about-us" scroll-bookmark="about-us" ng-click="activeSection=true" ng-init="activeSection=false"> <div class="page-content sub-content active-section">{{activeSection}} < ...

What could be the reason for ThemeProvider (Material UI) failing to function properly in this scenario?

I've encountered something puzzling with Material UI. Despite my experience with it, I can't seem to figure out why my H2 tag in the nested component is rendering in Times instead of Arial. I've double-checked the docs and my code, but the i ...

Tips on eliminating the header section in SlickGrid?

Is there a way to remove the header row in SlickGrid using CSS? I know there isn't an API for it, but maybe some CSS tricks can do the job. Any suggestions? Check out this example: Calling all CSS experts! I'm looking for assistance in modifyin ...

What is the best method to send the HTML button ID to a Python file through Django?

I have the following HTML code snippet that generates dynamic buttons: {% for i in loop_times %} <button type="submit" class="'btn btn-lg" name="{{ i }}" id="{{ i }}" onclick="alert(this.id)" formmethod="post"><a href="{% url 'button ...