Introduction
Sometimes you have a lot of information you want to disclose gradually. This is often the case with Frequently Asked Questions. An accordion is a perfect solution for this. Clicking on the title of the accordion expands the content area. You can see a demo on this web award website.
How it works
To create an accordion, add the following code to the front matter of your page:
---
accordion:
- title: this is item 1
content: Lorem ipsum dolor sit amet, consectetur adipiscing elit.
- title: this is item 2
content: Lorem ipsum dolor sit amet, consectetur adipiscing elit.
---
The code uses no javascript and uses the CSS ‘checkbox hack’ to toggle the content. The accordion deliberately refrains from setting the height of the content blocks. Calculating this height with javascript is required to add animation (slide down), but adds a lot of complexity. If you want to animate this accordion nevertheless, I would suggest to calculate the height during the ‘onclick’ and remove the height directly after the animation process. Calculating the height during the ‘window.resize’ seems more logical, but will slow down your website. Although I like animated accordions, I think that this CSS-only solution is more elegant. The code of the example above can be found here.
[expand]
<style>
ul.jekyllcodex_accordion {position: relative; margin: 1.4rem 0!important; border-bottom: 1px solid rgba(0,0,0,0.25); padding-bottom: 0;}
ul.jekyllcodex_accordion li {border-top: 1px solid rgba(0,0,0,0.25); list-style: none; margin-left: 0;}
ul.jekyllcodex_accordion li input {display: none;}
ul.jekyllcodex_accordion li label {display: block; cursor: pointer; padding: 0.75rem 2.4rem 0.75rem 0; margin: 0;}
ul.jekyllcodex_accordion li div {display: none; padding-bottom: 1.2rem;}
ul.jekyllcodex_accordion li input:checked + label {font-weight: bold;}
ul.jekyllcodex_accordion li input:checked + label + div {display: block;}
ul.jekyllcodex_accordion li label::before {content: "+"; font-weight: normal; font-size: 130%; line-height: 1.1rem; padding: 0; position: absolute; right: 0.5rem; transition: all 0.15s ease-in-out;}
ul.jekyllcodex_accordion li input:checked + label::before {transform: rotate(-45deg);}
</style>
<ul class="jekyllcodex_accordion">
{% for item in page.accordion %}
<li><input id="accordion{{ forloop.index }}" type="checkbox" /><label for="accordion{{ forloop.index }}">{{ item.title }}</label><div>{{ item.content | markdownify }}</div></li>
{% endfor %}
</ul>
[/expand]
Installation
Step 1. Download the file accordion.html
Step 2. Save the file in the ‘_includes’ directory of your project
Step 3. Make sure your front matter of your page looks like the example above
Step 4. Add the following line to your layout on the place where you want the form to appear:
{% include accordion.html %}