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

How to achieve divs with see-through text using CSS?

How can I create a CSS (non-HTML5) based website with a filled div that has a cutout revealing an image underneath? There are various overlays and images involved, making the use of static images inconvenient. Additionally, I anticipate needing to scale th ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

Instructions for removing all entries from a DynamoDB table

I am facing a challenge with deleting multiple items from a DynamoDB table. While the documentation suggests dropping and recreating the whole table, I want to avoid this approach as my table was created using AWS Amplify and I don't want to risk disr ...

displaying the identical image from various perspectives

I have an arrow image that I need to display in different angles - top, left, bottom, right. I was considering what would be the best approach: 1: Changing the image direction via CSS and loading the main image <img src="a.png"> <img src="a.png" ...

What could be causing my jQuery to malfunction after I include the .sqrt() function?

Seeking assistance in creating a grid of divs, I am working on finding the square root of the user's input to determine the height and width required to form a square. The code below is what I currently have: $('#size').click(function(){ $ ...

Effortless method for distributing NPM-loaded modules among various Browserify or Webpack bundles

Feeling frustrated trying to find a straightforward way to share code, required via NPM, across multiple Browserify or Webpack bundles. Is there a concept of a file "bridge" that can help? I'm not concerned about compile time (I know about watchify), ...

Stop Ajax requests when there are blank spaces in Typeahead.js

I've been experimenting with typeahead.js and utilizing the BloodHound remote feature to load data. Everything is functioning properly, except that when I input only spaces in the textbox, typeahead still makes an ajax call. I'm wondering if th ...

Tips on setting the default sorting order in AngularJS

I have implemented a custom order function in my controller with the following code: $scope.customOrder = function (item) { var empStatus = item.empState; switch (empStatus) { case 'Working': return 1; case & ...

Is it beneficial to display three.js on a <canvas> rather than a <div>?

I have come across examples in three.js that use: renderer = new THREE.WebGLRenderer( { canvas: document.querySelector( 'canvas' ) } ); This relates to a <canvas></canvas> element. On the contrary, there is another method: rendere ...

Why won't console.log function execute in this particular situation?

(function( $ ){ $.fn.openlayers = function( mapElementId, options ) { alert(console.log); console.log(options); ... } }); While attempting to enhance the capabilities of a JavaScript library, I encountered an unexpected issue. ...

The background appears only in the upper portion of the screen upon refreshing the table

Whenever the user clicks on the edit button or when the page is initially loading, a backdrop appears and disappears once the modal is displayed. The backdrop effectively highlights the entire page. However, after updating my table with data via Ajax witho ...

Display unique information according to the value in the form field (email domain)

I've developed an innovative ajax signup form that integrates jQuery and CSS3. The unique feature of this form is its multi-step process. In the first step, users are required to enter their email address and password. What sets this form apart is i ...

Using JQuery to create a button inside a Modal dialog box

My goal is to select a row within a Table that is located inside a Modal window, and then have a button ('newBtn') within that Modal window trigger a post request to the server with the selected id of the row. However, the issue I am encountering ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

PHP do-while loop triggers out of memory error while running SQL query code

While running the code below, the website crashes with the error: "Allowed memory size of 268435456 bytes exhausted (tried to allocate 254643 bytes)" $queID = "LCGQ00" . $ID; $sqlquecheck = "Select QueryID FROM Questions Where QueryID = & ...

Show a Toast in React without relying on useEffect to manage the state

I have successfully implemented the Toast functionality from react-bootstrap into my application using the provided code. However, I am unsure if it is necessary to utilize useEffect to set show with setShow(items.length > 0);. Would it be simpler to ...

"Obtaining header requests in node.js: A step-by-step guide

Currently, as I work on developing the elasticsearch API application, my task involves retrieving the header request from an AJAX call on the server side. The AJAX request is as follows: $.ajax({ url: 'http://localhost:3002/api/v1/getAutoSu ...

There seems to be a glitch with the functionality of the HighStocks Tooltip

I've implemented a modified version of the example from highcharts: $(function () { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) { // Create the chart $('#co ...

The hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...