How to make an accordion in HTML CSS

Make an accordion with HTML & CSS. Learn how to create a collapsible content panel with a stylish example.

Create an Accordion with HTML and CSS

An accordion is a great way to display a lot of information in a smaller space. It is commonly used for menus, FAQs, and other sections on a website. Creating an accordion with HTML and CSS is a straightforward and easy process.

Step 1: Create the HTML Structure

The HTML structure for creating an accordion is relatively simple. To start, we create a <ul> element, which will contain the accordion items. Inside the <ul>, we will create each accordion item as a <li> element. Inside each <li>, we will create a <div> element that will contain the title of the item and the content. Inside the <div>, we will create a <h3> element for the title and a <p> element for the content.

<ul>
  <li>
    <div>
      <h3>Title 1</h3>
      <p>Content 1</p>
    </div>
  </li>
  <li>
    <div>
      <h3>Title 2</h3>
      <p>Content 2</p>
    </div>
  </li>
  <li>
    <div>
      <h3>Title 3</h3>
      <p>Content 3</p>
    </div>
  </li>
</ul>

Step 2: Add CSS Styles

Now that we have the HTML structure in place, we can start styling it with CSS. We will start by adding some basic styles to the <ul> and <li> elements. We will set the list items to be displayed inline, add some padding, and a border. We will also set the list items to be hidden by default.

ul {
  list-style: none;
  padding: 0;
}

li {
  display: inline-block;
  padding: 10px;
  border: 1px solid #ccc;
  position: relative;
  overflow: hidden;
  max-height: 0;
}

Next, we will style the <h3> element. We will set the color and font-size, and also add a cursor property so that when the user hovers over the title, it will change to a pointer.

h3 {
  color: #000;
  font-size: 16px;
  cursor: pointer;
}

Step 3: Add JavaScript Functionality

Finally, we will add the JavaScript to make the accordion work. We will start by selecting all the <h3> elements on the page and adding an event listener for the click event. When a <h3> is clicked, we will toggle the open class on the <li> element that contains the <h3>.

const titles = document.querySelectorAll('h3');

titles.forEach(title => {
  title.addEventListener('click', () => {
    const parent = title.parentElement;
    parent.classList.toggle('open');
  });
});

The open class will contain the styles to transition the <li> element from a closed state to an open state. We will set the max-height property to a large number so that the transition will appear smooth. We will also set the transition property to animate the transition.

.open {
  max-height: 500px;
  transition: max-height .2s ease-out;
}

That’s it! We have now created an accordion with HTML, CSS, and JavaScript. You can see a working example of this code here.

Answers (0)