In a previous tutorial I showed you how you can create a Pure CSS Image Lightbox, and we used the CSS :target selector. Today I’m going to show you how you can create a Pure CSS Accordion using the same method.

Create a Pure CSS Accordion

[tutorial_details]

Let’s get started. Go ahead and create a new HTML document, and add the following code into it.

<ul id="accordion">
    <li>
        <a href="#tab1"><h2>Box One</h2></a>
        <section id="tab1" class="content">
            <p>Content for Box One</p>
        </section>
    </li>
    <li>
        <a href="#tab2"><h2>Box Two</h2></a>
        <section id="tab2" class="content">
            <p>Content for Box Two</p>
        </section>
    </li>
    <li>
        <a href="#tab3"><h2>Box Three</h2></a>
        <section id="tab3" class="content">
            <p>Content for Box Three</p>
        </section>
    </li>
</ul>

In the code above, we create a list, and each list item has two parts. The first one is a H2 header, this is the head of the box, this is always visible and when you click it, the content part associated with it, displays and the others will be hidden.

To be able to use the :target selector, we added an anchor tag ( < a > ) to each box with the destination of #tab1, #tab2, #tab3 etc… This MUST match with the ID of the item’s Content ID. And with this, if we click the First Box’s header, then it’s content will be show, if we click the second one, the first one will be hidden and the second Box’s content will be show.

Now to make this all work, we need to add some CSS to our project. See below:

#accordion {
    margin:0 auto;
    width:400px;
    }
ul {
    margin:0;
    padding:0;
    }
ul li {
    list-style:none;
    border:1px 1px 1px 1px #efefef solid;
    background-color:#34495e;
    }
ul li h2 {
    margin:0;
    padding:10px;
    font-size:18px;
    font-family:Arial, Helvetica, sans-serif;
    color:#ecf0f1;
    border-bottom:1px #efefef solid;
    }
ul li a {
    
    }
ul li .content {
    height: 0;
    overflow:hidden;
    }
ul li .content:target {
    height:auto;
    border-bottom:1px #efefef solid;
    }
ul li .content p {
    padding:10px;
    color:#ecf0f1;
    }

The two main part in the code above, are the ul li .content and ul li .content:target. These two make this all work. The first one hides each content box, and the second one, displayed the content of the box we clicked one.

If you liked and learned something from this tutorial, consider sharing it with your friends and followers and if you have any questions of feedback, feel free to leave a comment down below!