Animatoring Animatoring - 2 months ago 19
CSS Question

Pure CSS: unlimited nesting accordion?

Is there a way to create a pure CSS and html unlimited nesting accordion? I have below as a base but when I try to nest an accordion within an accordion it doesn't seem to work. For example,

Main Accordion


  • Subaccordion1
    Content for subaccordion1

  • Subaccordion2
    Content for subaccordion2



I would like the main accordion to contain both subaccordions 1 and 2. When I added a second accordion to the main accordion either the main accordion would not contain the second one or subaccordion2 would become indented one level lower than subaccordion1 when I tried different ways to moving the code so far.



<!doctype html>
<html class="no-js" lang="en">

<head>
<meta charset='UTF-8'>

<title>Notes</title>

<!--[if IE]>
<style type="text/css">
.box { display: block; }
#box { overflow: hidden;position: relative; }
b { position: absolute; top: 0px; right: 0px; width:1px; height: 251px; overflow: hidden; text-indent: -9999px; }
</style>
<![endif]-->

</head>

<body>
<!-- Styles for collapsible list -->
<style>
.collapsibleList li > input + * {
display: none;
}

.collapsibleList li > input:checked + * {
display: block;
}

.collapsibleList li > input {
display: none;
}

.collapsibleList label {
cursor: pointer;
}
</style>
<!-- Styles for collapsible list -->

<!-- Content start here -->
<!-- Main Accordion start -->
<ul class="collapsibleList">
<li>
<label for="mylist-node1"><font color="#2c84fc"><u>Main Accordion</u></font></label>
<input type="checkbox" id="mylist-node1" />


<!-- subaccordions start -->
<!-- Subaccordion1 start -->
<ul class="collapsibleList">
<li>
<label for="mylist-node2"><font color="#2c84fc"><u>Subaccordion1</u></font></label>
<input type="checkbox" id="mylist-node2" />
<ul>
<li>Subaccordion 1 content
</li>
</ul>
</li>
</ul>
<!-- subaccordion1 end -->

<!-- Subaccordion2 start -->
<ul class="collapsibleList">
<li>
<label for="mylist-node3"><font color="#2c84fc"><u>Subaccordion2</u></font></label>
<input type="checkbox" id="mylist-node3" />
<ul>
<li>Subaccordion 2 content
</li>
</ul>
</li>
</ul>
<!-- subaccordion2 end -->

<!-- sub accordions end -->


</li>
</ul>
<!-- Main Accordion end -->
<!-- Content end here -->

</body>

</html>




Answer

You are using Adjacent selectors. This selects only the immediate sibling.

input + *
input:checked + *

You can change that to a General sibling selector. That should select all siblings at the same level.

input ~ *
input:checked ~ *
Comments