What's the best way to align divs vertically in a compact layout?

Update

The reason I require this specific behavior is to ensure that all my content remains in chronological order, both on the web page and in the HTML structure. This way, even if the layout collapses into a single column on smaller screens, the content still maintains its correct sequence.

                1 div -->  1                2 divs  -->  1
                1 | 2      2                1 | 2        3
                3 | 4      3                3 | 4        5
                5 |        4                5 |          2
                           5                             4

My website features two columns of content, each occupying 50% of the width. The content is displayed within toggleable boxes that expand or collapse when their headers are clicked on.

When a box on the right side is minimized, the box below it adjusts to fill the space, maintaining proper alignment:

However, minimizing a box on the left leads to a gap between it and the neighboring box on the right, proportional to the size of the adjacent box:

Here's some pseudo code representing the layout:

<div class="full_width">
    <div class="box">       <-- box 1
        <h1>Heading</h1>
        <div>Content.</div>
    </div>
    <div class="box">       <-- box 2
        <h1>Heading</h1>
        <div>Content.</div>
    </div>
    <div class="box">       <-- box 3
        <h1>Heading</h1>
        <div>Content.</div>
    </div>
</div>

Based on my understanding, due to the current HTML structure, box 3 cannot be positioned above the bottom of box 2. Is there any workaround for this issue?

A JavaScript solution would suffice, especially since the problem arises only on pages with JavaScript enabled.

Additional Information

-To witness the issue live on my website, you will need JavaScript and a monitor wider than 1000px as the layout collapses below that width and toggling functionality relies on JavaScript.

-While I could separate the content into fixed columns to prevent these issues, that doesn't align with the desired functionality.

Answer №1

Have you considered utilizing CSS3 columns for your layout? One advantage of the code snippet below is that the columns will automatically adjust and stack responsively on smaller screens. Feel free to adapt the following code to better fit your specific requirements:

HTML

<div class='full_width'>
    <div class="box">
        <h1>Title</h1>
        <div>Content.</div>
    </div>
    <div class="box">
        <h1>Title</h1>
        <div>Content.</div>
    </div>
    <div class="box">
        <h1>Title</h1>
        <div>Content.</div>
    </div>
    <div class="box">
        <h1>Title</h1>
        <div>Content.</div>
    </div>
    <div class="box">
        <h1>Title</h1>
        <div>Content.</div>
    </div>
</div>

CSS

html, body {
    width:100%;
    margin:0;
    padding:0;
}
.full_width{
    -webkit-column-width: 20em;
    -webkit-column-gap: 2em;
    -webkit-column-count: 2;
    -moz-column-width: 20em;
    -moz-column-gap: 2em;
    -moz-column-count: 2;
    -ms-column-width: 20em;
    -ms-column-gap: 2em;
    -ms-column-count: 2;
    column-width: 20em;
    column-gap: 2em;
    column-count: 2;
}
.box{
    break-inside: avoid-column;
    -webkit-column-break-inside: avoid;
    page-break-inside: avoid;
    width:100%;
    box-sizing:border-box;
}


.box(:first-of-type) {
    margin: 20px 0;
}

Answer №2

After writing this function and implementing it to run on page load and whenever a box finishes changing size, I was surprised by how simple the solution turned out to be.

function align_columns() {
    $('.box').each(function() {
        // check if box is on left side of screen
        if ($(this).offset().left < 50) {
            $(this).css("float", "left");
        } else {
            $(this).css("float", "right")
        }
    });
}

Prior to using this function, we were experiencing alignment issues:

The boxes now fit neatly in the correct order down the page:

Answer №3

It is perplexing to me why you are hesitant about having two individual divs, each dedicated to a specific column. By structuring it this way, the styling can be easily controlled through CSS and you will have the flexibility to switch the content from left to right effortlessly.

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

Exploring Three.js: The challenge of loading multiple material objects

I am currently using three.js and facing an issue while loading multiple material objects. The problem arises when I rotate the code, causing unexpected behavior with the second material object. Ideally, I want the first material object [cubeMaterial] to r ...

An issue with Destination-Out Composition in HTML5 Canvas

While working on a canvas, I have encountered an issue with deleting a portion of a curve I have drawn. Specifically, I need to remove the last 25% of the curve after it is complete and keep only the first 75%. However, when attempting to delete the lines ...

Guide to setting up 2-factor authentication on GitHub using an AJAX request

My task is to query GitHub for all open pulls, but I'm new to this and don't have anyone to turn to for guidance. The only resources I've found so far are the documentation on . I came across a solution on that explains how to provide a us ...

Utilizing TIMING=1 with eslint to evaluate rule efficiency on Windows operating system

On the official ESLint website, there is a section titled Per-rule Performance. It explains that "setting the TIMING environment variable will prompt the display of the ten longest-running rules upon linting completion, showing their individual runn ...

How can we effortlessly generate a times table using For loops and arrays?

As someone new to JavaScript, I am eager to learn. My goal is to create two "for" loops: one to save the values of the 6 times table up to 12x6 into an array called timesTable, and another to display these values in the console (e.g., 0 x 6 = 0). Thank y ...

Ways to enhance the Response in Opine (Deno framework)

Here is my question: Is there a way to extend the response in Opine (Deno framework) in order to create custom responses? For instance, I would like to have the ability to use: res.success(message) Instead of having to set HTTP codes manually each time ...

Update the content within every <td> element using AJAX/JQUERY on a table created from JSP

I have a database filled with descriptions and corresponding ID numbers. The table displays them like this: index.jsp <table> <tr> <td>Name:</td> <td>Id:</td> </tr> <c:forEach items ...

Load images in advance using this script

Using a script to load images on two websites, the image is placed inside a div with the ID div-to-load-external-image Encountering an issue where PageSpeed Insights advises to preload these images, seeking guidance... Any assistance will be appreciated. ...

Unable to disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none. I have attempted to achieve this functionality using jQuery without s ...

The central navigation system of the Owl Carousel

I am currently using the owl carousel plugin and I am struggling to figure out how to center align the navigation vertically while also using the autoHeight option. http://codepen.io/anon/pen/jJAHL I have attempted the following code snippet, but it seem ...

Apply design to a dynamically generated JavaScript id using Stylus

Currently, I am utilizing a jquery datepicker widget, and my goal is to customize the CSS for its input field. However, it seems that the id assigned to that field is dynamically generated upon page load: <input type="text" id="dp1382434269539" style= ...

Tips for creating animations with multiple elements that share the same classes

I am trying to create expandable boxes that can open onclick and close again by clicking on the X. The issue I'm facing is that the close jQuery function isn't working. However, my main concern is how to optimize the code so it doesn't becom ...

Guide to managing AutoComplete {onChange} in MUI version 5 with a personalized hook

Currently, I am utilizing a custom hook that manages the validation and handling of the onChange function. For most components like input, select, and textField, I have no trouble with handling the onChange event using the syntax below: The code snippet ...

The issue of flickering while scrolling occurs when transitioning to a new page in Angular

I have encountered an unusual issue in my Angular 13 + Bootstrap 5 application. When accessing a scrollable page on small screen devices, the scrolling function does not work properly and causes the page to flicker. I observed that this problem does not o ...

Experiencing an Issue with NGINX Loading Vue 3 Vite SPA as a Blank White Page

I currently have the following NGINX configuration set up: events { worker_connections 1024; } http { server { listen 80; server_name localhost; location / { root C:/test; index index.html; ...

Encountering unidentified data leading to the error message "Query data must be defined"

Currently, I'm utilizing Next.js to develop a project for my portfolio. In order to manage the API, I decided to implement both Tanstack query and Axios. The issue arises when attempting to retrieve the data as an error surfaces. Oddly enough, while ...

What strategies can I use to optimize the code for the function provided?

This function allows for the dynamic display of select tags for location selection based on employee designation. The current code functions correctly, but I believe it can be optimized further. // Function to activate different location options based on e ...

What is the best way to create a gradual color change in each individual cell instead of changing all at once?

Looking for some help with a grid I'm working on. I've got the cells changing colors like I want them to, but they're all changing at once. What I really need is for them to light up in a specific order - Yellow, Green, Blue, White, Orange. ...

Connecting to an element within a separate node (XSLT)

I have an XML document that includes a list of companies. My goal is to use XSLT to create links that point to the <link> child of the next company node. To provide a clearer picture, here is a snippet of sample XML data I am working with: <portf ...

Display a remote page on hover using Javascript, CSS, and HTML without providing any clickable link

How can I display a preview of another page within a div container without actually making the text clickable? I want the preview to show when the mouse hovers over specific text, but I need the original text to stay on the main page. I've experiment ...