CSS-Only Accordions

Intro/rationale

This is a lightweight site, and I wanted to add some accordion-style functionality while preserving the load speed of a site free of javascript and jquery. This is one way to do that.

The code in action

This is some content that we want to show or hide on click.

HTML


      <input type="checkbox" class="trigger-checkbox" id="accordion-trigger">
      <!--This line creates a checkbox. When checked, we'll show the accordion content, when unchecked, we'll hide it.-->

      <label for="accordion-trigger">This is a header/accordion button</label>
      <!-- the "for" clause here links this label to the matching id in the input tag, so a click will check the box
      Then, we can hide the box, and style the label however we might choose. -->

      <div class="accordion-content">
      <!--We need a block to show or hide,and a div is the easiest way to create that.-->
        <p> This is some content that we want to show or hide on click.</p>
        <!--We can put whatever content we want in the .accordion-content div.-->

    

CSS


        label {
            text-align: left;
            display:block;
            font-family: 'Rambla', sans-serif;
            color:slateblue;
            font-size: 2.5em;
            margin-top: 0;
            @media (min-width: 980px) {
              color:grey;
            }
        }

        @mixin transition-height($duration, $style) {
          transition: max-height $duration $style;
        }

        .accordion-content{
          max-height: 0;
          overflow:hidden;
           @include transition-height(.25s, ease);
        }
        .trigger-checkbox{
          display:none;
          &:checked {
            ~ .accordion-content {
              max-height: 3000px;
              @include transition-height(1s, linear);
            }
            ~ label {
              text-align: center;
            }
        }
        }

        /* Add transitions so the headers slide out */

      

Final Thoughts

These CSS-only accordions are lightweight, blindingly fast, and functional for a majority of use cases. I'm a big fan of human-parsable code, so...it's a thing! The next step is to have some sort of visual trigger--when I figure that out, I'll update the tutorial!