How to create a collapsible section with CSS and JavaScript?

CSSWeb DevelopmentFront End TechnologyJavascript

To create a collapsible section with CSS and JavaScript, the code is as follows −


 Live Demo

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .collapse {
      background-color: rgb(83, 186, 255);
      color: white;
      cursor: pointer;
      padding: 18px;
      width: 100%;
      border: none;
      text-align: left;
      outline: none;
      font-size: 18px;
   .active, .collapse:hover {
      background-color: rgb(34, 85, 160);
   .content {
      padding: 0 18px;
      display: none;
      overflow: hidden;
      background-color: #b6fdff;
      font-size: 18px;
<h1>Collapsible Example</h1>
<h2>Click on the below collapsible to show the contents</h2>
<button type="button" class="collapse">Open Collapsible</button>
<div class="content">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Optio, ducimus!
   var collapse = document.querySelector(".collapse");
   var i;
   collapse.addEventListener("click", function() {
      var content = this.nextElementSibling;
      if ( === "block") { = "none";
      } else { = "block";


The above code will produce the following output −

On clicking the “Open Collapsible” −

Updated on 07-May-2020 11:18:25