What is the best way to split a single column into two using blocks?

I am working with a container that currently has all its blocks lined up in a column. I need to divide them into two columns, with 5 blocks in each. Unfortunately, the plugin I am using generates the code for me and does not allow me to insert my own div elements. How can I split these blocks into two columns using javascript?

<div class="container">

  <div> < /div>
  <div> < /div>
  <div> < /div>
  <div> < /div>
  <div> < /div>
  <div> < /div>
  <div> < /div>
  <div> < /div>
  <div> < /div>
  <div> < /div>

</div>

The desired output is as follows:

<div class="container">
  <div class="col-first">
    <div> < /div>
    <div> < /div>
    <div> < /div>
    <div> < /div>
    <div> < /div>
  </div>
  <div class="col-second">
    <div> < /div>
    <div> < /div>
    <div> < /div>
    <div> < /div>
    <div> < /div>
  </div>

</div>

.container{
 display: flex;
}

Answer №1

i have written a script that iterates over the children of a div, divides it in half, and places the first half in one div and the second half in another div. i hope this solution is helpful for you

//we start by calculating the number of children in the container and ensure we don't get half values using Math.ceil
let length = Math.ceil($(".container").children().length / 2);
//store the current html content before adding divs
let children = $(".container").children();
//once we have the count, we create two new divs for the first and second halves
$(".container").append("<div class='first-half half'></div><div class='second-half half'></div>");

//putting the second half of items into the second half div
$(children).slice(length).appendTo(".second-half");
//and moving the first half
$(children).slice(0, length).appendTo(".first-half");
.container{
  background: blue;
  height: fit-content;
}
div{
  width: 50px;
  height: 20px;
  border: 1px solid black;
}
.first-half{
  border: 2px solid green;
  height: fit-content;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">

  <div>this should be in the first half </div>
  <div> </div>
  <div> </div>
  <div> </div>
  <div> </div>
  <div> </div>
  <div> </div>
  <div> </div>
  <div> </div>
  <div> this in the second</div>

</div>

focus on the html output and ignore the css styling provided

Answer №2

If you want to divide the content of the .container into 2 columns, you can add the following styles:

.container {
    display: grid;
    grid-template-columns: 1fr 1fr;
}

.container div {
    display: inline-grid;
}

To implement this without those classes, you can include them in your stylesheet and use JavaScript to group them into two. Here's how you do it:

Create a function that counts the number of divs within the .container class using jQuery:

let all = $('.container').children('div').length;

Then, divide the total by 2 to determine the first column:

let col1 = all/2;

Round up the value to handle odd numbers properly. For example, if there are 10 divs, col1 will be 5. If there are 9 divs, col1 will still be 5.

col1 = Math.ceil(col1);

Next, apply the necessary styles using a loop and wrap them with another div block with these styles:

$(document).ready(function(){
  let all = $('.container').children('div').length;
  let col1 = all/2;
  col1 = Math.ceil(col1);
  for(let i = 0; i < all; i++){
    if(i < col1){
      $('.container').children('div').eq(i).addClass('col1');
    }
    else {
      $('.container').children('div').eq(i).addClass('col2');
    }
  }
  $('.container').children('.col1').wrapAll('<div class="col-first">');
  $('.container').children('.col2').wrapAll('<div class="col-second">');
});
.container {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.col-first, .col-second {
  display: flex;
  flex-direction: column;
  width: 50%;
}

/* Additional styles (optional) */
.container .elem {
  display: block;
  width: 50px;
  height: 60px;
  position: relative;
  background-color: green;
  margin: 4px;
}

.col-second .elem.col2 {
  background-color: steelblue;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<div class="container">
  <div class="elem"></div>
  <div class="elem"></div>
  <div class="elem"></div>
  <div class="elem"></div>
  <div class="elem"></div>
  <div class="elem"></div>
  <div class="elem"></div>
  <div class="elem"></div>
  <div class="elem"></div>
</div>

I've included '.elem' classes so you can observe how the elements behave.

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

Align an element in the middle next to its sibling element

Utilizing the pagination component in Bootstrap, the structure of the pagination itself is quite straightforward: <ul class="pagination"> <li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true">&laquo; ...

Combine angular ui router templates using grunt into a single file

Currently, I am working on an angular-ui-router project that consists of 150 files scattered all over. My goal is to create a grunt task that will merge all these files into a single index.html file structured like this: <script type="text/ng-template" ...

Changes made to index.php are not reflecting on the WordPress website

Currently making changes to my WordPress theme and just included a new div with the class "sidebar." However, I'm encountering an issue where it's not updating on the homepage of the website. Strangely enough, the stylesheet does seem to be updat ...

Guide to utilizing AJAX to retrieve a value from a controller and display it in a popup

I need assistance with retrieving data from a controller and displaying it in an HTML pop-up when a button is clicked. Currently, the pop-up shows up when the button is clicked, but the data is not being loaded. I would like the values to be loaded and d ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website. Here's how it works at the moment: const ...

Using a variable with the :contains selector

function checkAndUpdateStatus(newName) { $('#myTable').children('tr').remove(":contains('" + newName + "')"); }; The function above is attempting to remove table rows in 'myTable' containing a string matching the ...

What is the best way to adjust a CSS width using the output from a JavaScript function?

I am facing a challenge with a GridView within a div wrapper. The row headers along the left side need to always be visible. So far, this setup is working fine. However, I need the wrapper to have a variable width to adjust to the browser size. Although I ...

Rearrange the sequence of specific child elements within the Div

Is there a way to reverse the order of specific div's children elements using just CSS? For instance: I need <div id="parent"> <a>A</a> <a>B</a> <a>C</a> <a>D</a> &l ...

Obtain the complete file path using JavaScript

Imagine you have a web application utilizing NodeJS and ReactJS, both working on your local machine. In this setup, NodeJS is capable of accepting files selected from the ReactJS GUI via a simple file upload feature, like so: <input type="file" id="fil ...

Transmitting special symbols through Socket.io

I've been working on a small project based on Socketio 0.9 and everything is running smoothly, except for a minor problem with special characters. In the web client, I am creating a dynamic JSON object using JavaScript that is then emitted to the ser ...

How to stop AngularJS onClick event from causing scroll to jump to top of

As I work on developing a website using Angular JS and Bootstrap, I encountered an issue with the hamburger menu button on my homepage. Whenever I scroll halfway down the page and click the hamburger icon, it automatically scrolls me back to the top of the ...

The Laravel Mix Hot Module Replacement (HMR) server fails to start up

Laravel Mix Version: 6.0.43 Node Version (node -v): 16.13.1 NPM Version (npm -v): 8.1.2 OS: Windows 10 21h2 Description: Encountering an issue on a fresh installation of Laravel and other existing projects. When running npm run hot, the script tag sourc ...

Using Node.JS to retrieve values of form fields

I am working with Node.js without using any frameworks (specifically without express). Here is my current code snippet: const { headers, method, url } = req; let body = []; req.on('error', (err) => { console.error(err); }).on(&apos ...

Achieving a scrollable div with ng-repeat

I have implemented ng-repeat to showcase some messages, and I am attempting to create a scrollable "message_area" as the messages overflow naturally over time. However, my current code is not delivering the desired outcome. <div class="main_area"> ...

Divide a string into separate numbers using JavaScript

This snippet of code is designed to search the table #operations for all instances of <td> elements with the dynamic class ".fuel "+ACID: let k = 0; let ac_fuel = 0; parsed.data.forEach(arrayWithinData => { let ACID = parsed.data[k][0]; ...

Removing outline from a Material UI button can be done using a breakpoint

Is there a way to remove the outlined variant for small, medium, and down breakpoints? I have attempted the following approach: const selectedVariant = theme.breakpoints.down('md') ? '' : 'outlined'; <Button name="buy ...

Choose the number that is nearest to the options given in the list

I am faced with a challenge involving a list of numbers and an input form where users can enter any number, which I want to automatically convert to the closest number from my list. My list includes random numbers such as 1, 5, 10, 12, 19, 23, 100, 400, 9 ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

Is there a method to introduce a line break for each piece of data that is shown?

I am currently working with an array and have successfully displayed it on the screen. My inquiry is whether it is feasible to insert a line break for each of the data points it presents. { name: "cartItems", label: "Product Name ...