How to create Accordion using HTML CSS and javascript

A well-known design pattern is the accordion. The accordion gives a lot of information at once, and it also helps with maximizing space on your website because you can include more content without taking up too much space. There are two ways to create an accordion: by using CSS or JavaScript. In this blog post, we will show you how to use both methods in order to create an accordion for your website!

What is an accordion?

The accordion is a container of elements that can be opened and closed. The title or header element will usually have the “active” class, which means it has to be clicked for the corresponding block on an Accordion to open.

Accordions are usually used to show content that can be closed when you do not need it. For example, if there is a list of headers with text and images which should only occupy the space they take up on the screen but allow you to scroll through them without cluttering your viewport, an accordion might help display these items in a more compact way than using one long scrolling page would.

It allows you to create a widget with any number of panels inside it. A click on any panel will make that panel active while keeping all other panels closed (or vice versa).

How to create a basic accordion with CSS

Create a container for the accordion by giving it an ID and adding some CSS styles. The code below has been added to this blog post’s HTML in order to give you an idea of what we’re working with:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"> 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
  <style>
        *{margin: 0; padding: 0; box-sizing: border-box;}
        .accordion_container{max-width: 400px; padding: 10px; margin: auto; border: 1px solid #cccccc; color: #ffffff; }
        .accordion{display: flex; flex-direction: column; flex-basis: 100%; align-items: center;}
        header{background-color: #264653;padding: 10px 5px;width: 100%; cursor: pointer; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;}
        header:last-child{margin-bottom: 0;}
        section{ line-height: 24px; max-height: 0; overflow: hidden; transition: max-height 400ms; color: #333333;}
        .active + section{max-height: 400px;overflow: visible;  transition: max-height 100ms;}
    </style>

</head>
<body>
   <div class="accordion_container">
        <div class="accordion">
            <header>
                <h2> Lorem ipsum </h2>
                <i class="fas fa-plus"></i>
                </header>
                <section>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel aliquam obcaecati id doloribus consequatur facilis sit quos possimus ducimus iure.</p>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero, tempora? Reprehenderit quisquam voluptate inventore optio accusamus? Magni eos nesciunt tempore asperiores explicabo, voluptatum aspernatur itaque nulla? Dolorum optio consectetur rem quia nulla quae facilis iste voluptas maiores quam, suscipit natus molestiae provident nemo saepe assumenda quod quasi numquam doloremque? Illo.</p>
                    <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Iure cumque odio accusamus modi eos eligendi illo aspernatur asperiores iusto reprehenderit.</p>
                </section>
                
        </div>
        <div class="accordion">
            <header>
                <h2> Lorem ipsum </h2>
                <i class="fas fa-plus"></i>
                </header>
                <section>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel aliquam obcaecati id doloribus consequatur facilis sit quos possimus ducimus iure.</p>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero, tempora? Reprehenderit quisquam voluptate inventore optio accusamus? Magni eos nesciunt tempore asperiores explicabo, voluptatum aspernatur itaque nulla? Dolorum optio consectetur rem quia nulla quae facilis iste voluptas maiores quam, suscipit natus molestiae provident nemo saepe assumenda quod quasi numquam doloremque? Illo.</p>
                    <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Iure cumque odio accusamus modi eos eligendi illo aspernatur asperiores iusto reprehenderit.</p>
                </section>
                
        </div>
       

   </div> 


   <script>
    
    const header = document.querySelectorAll('header')
    

header.forEach(element => {
    element.addEventListener('click', ()=>{
        element.classList.toggle('active')
           icon = element.lastElementChild
   if(element.classList.contains('active'))
       {
           icon.classList.add('fa-minus')
           icon.classList.remove('fa-plus')
       }
       else{
        icon.classList.remove('fa-minus')
           icon.classList.add('fa-plus')
       } 
    })
});


  </script>
</body>
</html>
Accordion using css and javascript only

How to create a responsive accordion using javascript and CSS

We will be using CSS and a little bit of JavaScript to create an accordion with a responsive design. The first step is to define the overall structure, including adding some basic HTML elements for each slide such as anchors and labels. This code should go in the head section of your page:

Now it’s just about filling up those slides! Each “slide” can be a paragraph, image, or whatever you want. You can use the same HTML elements as we did before:

Now comes the fun part – adding some CSS to animate each slide! This is where things get really interesting and unique because now we have total control over how our accordion will look in all browsers. We’ll create an animation for when one panel opens (slide-show) and another animation for when it closes (fade). Let’s start with this snippet of CSS applied to your first “panel” element:

Why use an accordion for your website design

One of the most popular design trends in website layout is to use a content accordion. The accordion can be used for all sorts of different things, from displaying product information on an e-commerce site, or providing long-form content that would otherwise not fit on one screen.

  • A content accordion will allow the reader to click on a button that expands out, revealing more information or images. This is an engaging way to present content because it makes users want to explore and find what they can find hidden in the fold of this long-form layout.
  • The accordion layout is also very space-efficient because it allows the user to explore without having too many things on one page, which can be overwhelming.
  • This design will save a lot of screen real estate and make your content much more accessible for mobile devices such as smartphones.
  • This design also helps to organize your content in a way that is easy for the user.
  • In some cases, using an accordion layout will help users skip over sections they are not interested in reading but still be able to see all of the items you want them to see. This can make it easier on them and less time-consuming because there’s no need for scrolling back up or spending so much time trying to find what they’re looking for.

Types of Accordions

There are many different types of accordions to choose from. Some people prefer the classic vertical scrolling design, while others may like the one that is horizontal and expands with more content when clicked on. You can also purchase an accordion plugin for your website if you do not have any coding experience or time limitations in order to make it easier for yourself.

Conclusion

I hope this blog post was helpful in giving you some insight into how to create accordions that work well on any website. If you have any questions or comments about the content, please feel free to let me know below!

Also Read : How to create a popup using CSS and JavaScript on hover

Leave a Comment