showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. Being new to these languages with just a month of experience, I am unsure how to achieve this layout.

document.querySelectorAll(".collapse__button").forEach(button =>{
    button.addEventListener("click", () =>{
        const collapseContent = button.nextElementSibling;
        button.classList.toggle("collapse__button--active");
        if (button.classList.contains("collapse__button--active")){
            collapseContent.style.maxHeight = collapseContent.scrollHeight + "px";


        }else{
            collapseContent.style.maxHeight = 0;
        }

    });

});
.collapse__button {
    /* display:  inline-block; */
    padding: 1em 2em ;
    background: var(--clr-dark);
    color: var(--clr-light);
    text-decoration: none;
    cursor: pointer;
    font-size: .8rem;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-weight: var(--fw-bold);
    transition: transform 200ms ease-in-out;
    max-width: 200px;
    margin: 5em 5em;
    border: 8px var(--clr-accent);
    border-radius: 20px;
  
   
  }

.collapse__button:hover{
    transform: scale(1.1);
    background: var(--clr-accent);
}


  .collapse__button::after{
      content: "\25be";
      float: right;
      transform: scale(1);
  }


.collapse__content{
    overflow: hidden;
    max-height: 0;
    transition: max-height 0.2s;
    padding: 0 15px;


}


  .collapse__button--active::after{
    content: "\25b4";
}

.Title{
    text-align: center;
}
        <section class = "Title">
            <p> Title of Example</p>




            <div class = "collapse">
                <button class = "collapse__button"> Example 1 </button> 
                    <div class="collapse__content">
                        <p>
                            writing
                        </p>
                    </div>
            </div>
            
            <div class = "collapse">
                <button class = "collapse__button"> Example 2 </button> 
                    <div class="collapse__content">
                        <p>
                            more writing
                        </p>
                    </div>
            </div>

Answer №1

If you prefer not to use Flexbox, you can achieve the desired layout using display:table.

The display:table property functions similar to an actual table; however, it is important to note that tables have semantic meaning and should not be used for purely layout purposes. For example, using tables for layout as shown below is considered poor practice:

.topbar {
  background-color: blue;
  color:white;
  width: 100%;
}
<table class="topbar">
<tr>
<td>Site Name</td>
<td><label>Search: <input type="search" /></label></td>
</tr>
</table>
While visually appearing like a top bar, screen readers may interpret it as a data table rather than a layout element.

document.querySelectorAll(".collapse__button").forEach(button => {
  button.addEventListener("click", () => {
    const collapseContent = button.nextElementSibling;
    button.classList.toggle("collapse__button--active");
    if (button.classList.contains("collapse__button--active")) {
      collapseContent.style.maxHeight = collapseContent.scrollHeight + "px";


    } else {
      collapseContent.style.maxHeight = 0;
    }

  });

});
.collapse__button {
  /* display:  inline-block; */
  padding: 1em 2em;
  background: var(--clr-dark);
  color: var(--clr-light);
  text-decoration: none;
  cursor: pointer;
  font-size: .8rem;
  text-transform: uppercase;
  letter-spacing: 2px;
  font-weight: var(--fw-bold);
  transition: transform 200ms ease-in-out;
  max-width: 200px;
  margin: 5em 5em;
  border: 8px var(--clr-accent);
  border-radius: 20px;
}
#wrapper {
  display: table;
}
.container {
  display: table-row;
}
.collapse {
  display: table-cell;
}
.collapse__button:hover {
  transform: scale(1.1);
  background: var(--clr-accent);
}

.collapse__button::after {
  content: "\25be";
  float: right;
  transform: scale(1);
}

.collapse__content {
  overflow: hidden;
  max-height: 0;
  transition: max-height 0.2s;
  padding: 0 15px;
}

.collapse__button--active::after {
  content: "\25b4";
}

.Title {
  text-align: center;
}
<section class="Title">
  <p> Title of Example</p>
  <div id="wrapper">
    <div class="container">
      <div class="collapse">
        <button class="collapse__button"> Example 1 </button>
        <div class="collapse__content">
          <p>
            writing
          </p>
        </div>
      </div>

      <div class="collapse">
        <button class="collapse__button"> Example 2 </button>
        <div class="collapse__content">
          <p>
            more writing
          </p>
        </div>
      </div>
    </div>
  </div>
</section>

https://i.sstatic.net/MEuUg.png

Answer №2

Consider creating a new div that encompasses both Example 1 and Example 2. Utilize FlexBox within this container to arrange them side by side.

My approach:

document.querySelectorAll(".collapse__button").forEach(button =>{
    button.addEventListener("click", () =>{
        const collapseContent = button.nextElementSibling;
        button.classList.toggle("collapse__button--active");
        if (button.classList.contains("collapse__button--active")){
            collapseContent.style.maxHeight = collapseContent.scrollHeight + "px";


        }else{
            collapseContent.style.maxHeight = 0;
        }

    });

});
.collapse__button {
    /* display:  inline-block; */
    padding: 1em 2em ;
    background: var(--clr-dark);
    color: var(--clr-light);
    text-decoration: none;
    cursor: pointer;
    font-size: .8rem;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-weight: var(--fw-bold);
    transition: transform 200ms ease-in-out;
    max-width: 200px;
    margin: 5em 5em;
    border: 8px var(--clr-accent);
    border-radius: 20px;
  
   
  }

.collapse__button:hover{
    transform: scale(1.1);
    background: var(--clr-accent);
}


  .collapse__button::after{
      content: "\25be";
      float: right;
      transform: scale(1);
  }


.collapse__content{
    overflow: hidden;
    max-height: 0;
    transition: max-height 0.2s;
    padding: 0 15px;


}

  .collapse__button--active::after{
    content: "\25b4";
}

.Title{
    text-align: center;
}

  
  .container {
    display: flex;
    justify-content: center;
  }
        <section class = "Title">
            <p> Title of Example</p>


            <div class="container">
            <div class = "collapse">
                <button class = "collapse__button"> Example 1 </button> 
                    <div class="collapse__content">
                        <p>
                            writing
                        </p>
                    </div>
            </div>
            
            <div class = "collapse">
                <button class = "collapse__button"> Example 2 </button> 
                    <div class="collapse__content">
                        <p>
                            more writing
                        </p>
                    </div>
            </div>
          </div>
</section>

Answer №3

 document.querySelectorAll(".collapse__button").forEach(button =>{
     button.addEventListener("click", () =>{
       const collapseContent = button.nextElementSibling;
      button.classList.toggle("collapse__button--active");
      if (button.classList.contains("collapse__button--active")){
                    collapseContent.style.maxHeight = collapseContent.scrollHeight + "px";
                }else{
                    collapseContent.style.maxHeight = 0;
                }

            });

        });
        .collapse__button {
            /* display:  inline-block; */
            padding: 1em 2em ;
            background: var(--clr-dark);
            color: var(--clr-light);
            text-decoration: none;
            cursor: pointer;
            font-size: .8rem;
            text-transform: uppercase;
            letter-spacing: 2px;
            font-weight: var(--fw-bold);
            transition: transform 200ms ease-in-out;
            max-width: 200px;
            margin: 5em 5em;
            border: 8px var(--clr-accent);
            border-radius: 20px;
          
           
          }

        .collapse__button:hover{
            transform: scale(1.1);
            background: var(--clr-accent);
        }


          .collapse__button::after{
              content: "\25be";
              float: right;
              transform: scale(1);
          }


        .collapse__content{
            overflow: hidden;
            max-height: 0;
            transition: max-height 0.2s;
            padding: 0 15px;


        }


          .collapse__button--active::after{
            content: "\25b4";
        }

        .Title{
            text-align: center;
        }

        .container {
        display: flex;
        }
<section class = "Title">
<p> Title of Example</p>

        <div class="container">
            <div class = "collapse">
               <button class = "collapse__button"> Example 1                      </button> 
               <div class="collapse__content">
                 <p>
                    writing
                   </p>
                </div>
         </div>
                    
             <div class = "collapse">
                 <button class = "collapse__button"> Example 2 </button> 
            <div class="collapse__content">
               <p>
                   more writing
                    </p>
                </div>
               </div>
          </div>

You did a great job. Simply enclose your two collapsing sections within a div container and apply CSS flexbox to that container, as I have done for you in the code. The JavaScript section required no changes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

confrontation arising between two PHP scripts due to conflicting functionalities within the MetaSlider plugin

Seeking assistance with the WordPress plugin metaslider, specifically involving two code snippets. The first one implements the "ken burns effect" while the second disables the "pause on action" feature. Strangely, the "pause on action" seems to interfere ...

Styling input groups with box shadows in Bootstrap 4

One issue I am encountering is the focus shadow that appears when the input text is focused. My goal is to have both the text input and the right button display a focus border. To illustrate this problem, I have created a JSfiddle: http://jsfiddle.net/a5u ...

Synchronizing information between different controllers using a service

After reading the discussion on this stackoverflow post, it seems like using services is the recommended way to transfer data between controllers. However, in my own testing on JSFiddle here, I encountered difficulties in detecting changes to my service w ...

Is there a method to change the name of a file and have it automatically updated in all other locations where it is referenced?

I need to change the name of an HTML file within Visual Studio Code, but this file is referenced in multiple other files. Is there a quick way to do this? Are there any shortcuts that will let me rename the file and automatically update all references in ...

The HTML 5 Validation is unsuccessful due to the presence of the "Attribute addthis:url not allowed on element a at this point." error

I am currently facing an issue on my MVC4 Project web page where I have implemented the ShareThis plugin to display share count for various posts. The code snippet looks like this: @{ string strShareThisURL = "addthis:url=\"" + mainURL +" ...

Script malfunctioning following an AJAX request

My page consists of a header where all my javascript is located. Within the body of the page, there is a link that triggers an ajax http request using vanilla JavaScript (not jQuery). This request retrieves a PHP form and injects it onto my page. The PHP ...

Steps for making a CSS hover box with two sections

Recently, I came across a helpful tip on Stack Overflow about creating a box when hovering over text using pure CSS. It was quite interesting to implement. I decided to experiment with the cursor position and placement as well. span{ background:#F8F8 ...

Troubiling Responsive Menu in React

I am currently working on developing a React Responsive Navigation with SCSS, but I am facing an issue. When I click on the hamburger button, nothing happens and the menu does not slide down in the mobile view. I tried inspecting the code in the browser to ...

Executing a script on a different HTML page without the need to reload it

I'm currently working on incorporating a notification system inspired by Facebook's design. This system will feature an icon in the header that, when clicked, reveals a drop-down containing a table of sorted notifications for the user. My goal is ...

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...

Contrasting include versus block in Jade

Can you explain the distinction between blocks and include in Jade template creation? How do you determine when to use each one? ...

Moving Angularjs table rows to another tableMoving table row from one Angular

I need a solution for transferring rows from one table to another. Here are the two tables involved: First Table: <table> <tr ng-repeat="row in items"> <td>{{row.PRODUCTDESCRIPTION}}</td> <td><inpu ...

"Efficiently refresh the DOM by updating it solely upon changes in the

Within my AngularJS application, I have observed that the DOM refreshes each time a function is called, even if no $scope variables have been altered by that function. I am utilizing an ng-repeat directive to generate a series of checkboxes, as demonstrat ...

Tips for shrinking a sticky header when scrolling using Angular and JavaScript

Looking for a way to modify the header component in an Angular application so that it shrinks as the user scrolls down while maintaining its sticky functionality. How can I adjust the display of the lower half of the header to show no text when the user s ...

Transforming JSON date format to a different one using Jackson libraries

My spring boot 1.3.5 application is using jackson with the dependency "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.5.0". Encountering an issue when a user inputs a date value in a format different than expected (mm/dd/yyyy) during a POST requ ...

Is it possible to configure Webpack/NextJs to handle a recurring import path mapping?

Exploring ways to streamline imports in my NextJs Project (v14.1.3), I'm interested in finding a method to modify the import statement below: import foo from 'path/to/foo/foo' To possibly simplify it to: import foo from 'path/to/foo&ap ...

The issue of VueRouter malfunctioning in history mode within Wordpress

I have integrated Vue into my Wordpress theme, but I am facing an issue with the router when setting mode: 'history'. The site goes blank and even after trying to configure the .htaccess file, nothing seems to work. My project is located in the V ...

A guide on performing CRUD operations on locally stored JSON data using React JS

Retrieve the JSON data from any endpoint and store it locally fetch("any endpoint") .then((response) => response.json()) .then((responseJson) => { this.state ={ data:responseJson } }) How to perform CRUD operations on a sample JSO ...

Update specific fields in a MySQL database using Express.js only if they are passed as parameters

After spending several days trying to set up a REST API, I found a helpful tutorial that explained the basics of sending requests and receiving responses. The only issue is that the tutorial uses MongoDB and Mongoose, while I'm working with MySQL. Due ...