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>

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

What could be causing my bounce animation to begin 50 pixels higher than its intended starting point?

Trying to create a bouncing effect on text Check out my attempt here. It seems like the bug is in this area. @keyframes bounce{ 0%, 40%{ transform:scale(2,.5) translate(0,100px); } 45%,55%{ transform:translate(0,-50px); } 55%, 100%{ ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

Menu that sorts items based on a specified range of values entered by the user

I'm looking to implement a customized filtering dropdown menu, similar to the one showcased on this website Currently, I have functioning filters that can select items based on a specific category. However, I want to enhance the functionality by inc ...

JavaScript - Transforming Name:ItemName/Value:ItemValue Pairs into Standard ItemName:ItemValue JSON Format

Looking to reformat JSON data? [{"name":"age","value":31}, {"name":"height (inches)","value":62}, {"name":"location","value":"Boston, MA"}, {"name":"gender","value":"male"}] If you want it to be in a different format: [{"age": 31}, {"height (inches)": 6 ...

Creating a rotating wheel using JavaScript that is activated by a key press event

I need some help with implementing a keystroke event in this code so that the spinning wheel can start based on a key press, like the spacebar. Any suggestions on how to achieve this? I have found an event code for keystrokes in JavaScript: document.body. ...

The program is designed to only allow up to two images to be wrapped

I'm struggling with a short jQuery program that I need help with. The problem is, I can't seem to get it to wrap more than two images in the same row. My goal is to create a website that side-scrolls, and I thought this approach would be the simp ...

Synchronization issues arise when attempting to update the localStorage

Whenever I switch to dark mode, the update doesn't reflect in _app unless I have two tabs opened and trigger it in one tab. Then, the other tab gets updated with dark mode toggled, but not the tab where I pressed the toggle. I am using useSettings in ...

When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project: wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' ))); As part of testing, I used an $http. ...

Having trouble transmitting parameters through ajax

I have been attempting to use ajax to send variables to a php page and then display them in a div, but unfortunately, it's not functioning as expected. Below is the HTML code: <div id="center"> <form> ...

I'm interested in knowing how to switch between two functions using Angular

I have developed a grocery list application where each row contains the name of a food item. The layout includes a left column for items that are not needed and a right column for items that are needed. Currently, I am able to change the state by clicking ...

Tips for effortlessly enlarging an element

When you click on "#sidebarnav>li", the following happens: 1) The second child of it - <ul> element will expand and its class toggles between "collapse" and "collapse in". 2) "#sidebarnav>li" will receive the "active" class. 3) The "aria-ex ...

Click the navigation bar to toggle it on and off

I have a script that creates a navbar. Currently, the dropdown menu only opens when hovered over. The issue arises when accessing this on a mobile browser, as the dropdown menu does not open. How can I modify this script to make the dropdown menu open wh ...

Images are not displayed when utilizing font-awesome on a MVC 5 website

I'm having an issue where adding font-awesome to the style bundle is causing images not to display correctly. Instead of showing the right icon, I am getting a transparent box. My style bundle configuration looks like this: bundles.Add(new StyleBund ...

Navigate to the initial visible element on the specified webpage via the page hash link

In my handlebars HTML template, I have a partial view that includes different pieces of content for desktop and mobile. I use different CSS classes to hide and show these elements accordingly. <div class='hideOnMobile showOnDesktop'> < ...

Github not recognizing CSS styles

Currently working on a website to showcase the games I've developed, but encountering issues with applying my CSS. The code can be found here. As a novice in HTML and CSS coding, I've tried numerous codes and tutorials without success. ...

Utilizing Google Web Fonts in Gatsby with Custom Styled Components

While using createGlobalStyle from styled-components for global styling, everything seems to be working fine except for applying Google fonts. I have tried multiple ways but can't seem to get it to work. Here's the code snippet: import { createG ...

Redirecting files from the file system to the emulator is not functioning properly

I am new to Phonegap and need help resolving this issue. In my application, I need to redirect to the List.html file when a button is clicked. Here is the code I have written: button1 function test() { window.location="/home/swift-03/phonegapexa ...

Utilize Selenium to extract information from a webpage, including content that is dynamically generated through JavaScript

Currently, I am facing a dilemma: my desire is to extract information from a webpage (for example, this one) regarding the apps that are available, and then store this data into a database. In my quest to achieve this task, I have opted to use crawler4j t ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

Implement a jQuery click event on a dynamically generated button in the code-behind

A button (Replybtn) is dynamically created when clicked in the code-behind file. --Default.aspx.cs-- protected void ReloadThePanelDetails_Click(object sender, EventArgs e) { litResultDetails.Text = litResultDetails.Text + "<button id='Replyb ...