Determine the combined width of each child element and divide it by two

I am working on a div that has multiple children inside. To achieve a horizontal layout, I need to set a width on the parent div so that the content flows from left to right. Instead of having all items in one row, I want them to be split into two rows. This means I will have to calculate the total width and then divide it by 2 to wrap the items onto another line.

Since the number of children is dynamic, using a fixed CSS value is not suitable for this scenario.

The structure of the markup will resemble this:

<div id="container">
  <figure>1</figure>
  <figure>2</figure>
  <figure>4</figure>
  <figure>5</figure>
  <figure>6</figure>
</div>

I would really appreciate assistance with this issue. While I have managed to determine the dimensions of a single element in the past, I am struggling to do it for a group.

Thank you in advance, Steve

Answer №1

Check out this demo for a solution: https://jsfiddle.net/d94j7hn2/

To achieve this effect, follow these steps:
- Set a fixed width for the figure on page load (specified in CSS)
- Find the total number of figures within the container
- Calculate how many figures should be displayed per row (aim for 2 rows).
- Ensure 2 rows are shown by using Math.ceil()
- Determine the width of each row by multiplying the number of figures per row by the figure's width.
- Adjust the container's width to match the calculated row width.

Here's the JavaScript code based on the logic above:

$(document).ready(function(){

    //Find the width of the figures
    var figure_width = $("#container figure").css("width").replace("px", "");

    //Get the total number of figures
    var num_figures = $("#container figure").length;

    //Calculate how many figures per row
    var num_row_figures = Math.ceil(num_figures / 2);

    //Calculate the total width
    var row_width = figure_width * num_row_figures;

    //Set the container's width to half of the total width
    $("#container").width(row_width);

});

I hope this explanation is helpful!
Best regards, Josh

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

Encountering an issue with Ajax code on initial execution

I've implemented an Ajax script on my PHP page to execute a PHP script upon clicking a button. However, the issue I am facing is that when I initially load the web page, the script does not run. But, if I click back and repeat the process, the script ...

At times, an InvalidArgumentError occurs stating: "The 'handle' parameter must be a string."

I have incorporated 'React-google-login' into my React project and now I am working on an automated test to make sure it functions correctly. try { await driver.get("http://localhost:3000/"); await driver.wait(until.elementLocated(By.xpath(` ...

The Bootstrap row snag causing text display issues

There seems to be a glitch when the first column has more text than the one next to it. Check out the screenshot provided for reference. Any suggestions on how to fix this issue in Bootstrap? https://i.sstatic.net/fSq68.png Live Demo: https://jsfiddle. ...

What exactly is the purpose of utilizing node js and can someone explain to me what constitutes a

After mastering HTML and CSS, I've started diving into JavaScript. However, I'm curious about Node.js. What exactly is it, why do I need it, and can you explain what a framework is in general? Sorry if these questions sound silly! ...

I am trying to center align this image, but for some reason, it's not cooperating

Attempting to center the image using margin-left: auto and margin-right: auto properties in the code snippet above has proven unsuccessful. The image is not aligning as desired. What could be causing this issue with the code? Are there any other techniq ...

Identifying errors in a React component upon loading

As I delve into my project, my main focus lies on detecting errors within a component. The ultimate goal is to seamlessly redirect to the home page upon error detection or display an alternate page for redirection. I am seeking a programmatic solution to ...

Trigger the jQuery function once the external URL loaded via AJAX is fully loaded

Currently, I am in the process of developing a hybrid mobile app for Android and I am relatively new to this technology. I have two functions in jQuery, A and B. Function A is responsible for making an AJAX request to retrieve data from 4 external PHP fi ...

Unable to install react-dom/test-utils using npm

I recently included two libraries in my package.json "devDependencies": { ... "react-dom/test-utils": "*", "react-test-renderer/shallow": "*" }, These were recommended by the React documentation to align with version 16 of the React ecosy ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

What are some ways to expand the width and increase the spacing of bootstrap cards?

On my website, I have created Bootstrap cards that are displayed on two different pages. One set of cards is shown on the landing page, where I am looking to increase the spacing between them. The other set appears on the books page, and I want to make t ...

What is the best way to handle promises within the context of updating state in React

Recently, I've been working on a React code snippet focused on creating a text input field. onChangeDestination(url, index) { this.setState(prevState => { const rules = [...prevState.rules]; rules[index] = { ...rules[index], url}; ...

The Navigation Bar in Vue Component Renders Incorrectly due to Bootstrap Integration

I am facing an issue with my Bootstrap navbar not displaying correctly within my Vue component. It is appearing as a stacked greyed out button, almost like it's assuming it's on a small device. https://i.sstatic.net/yoPvO.png You can find the c ...

I'm curious, what's your strategy for handling the Gutenberg block previews in the backend?

Is there a way to customize Gutenberg block previews in the WordPress admin area? For instance: If I create a block using Bootstrap and my own custom CSS, will WordPress load Bootstrap and my CSS to show a preview in the admin area? ...

Is there a way to ensure that the JSON data and the image appear on the same row with some spacing between them?

Trying to display JSON data with images and text side by side but facing issues where the text wraps below the image instead. How can I fix this layout to show text next to the image? Flex-wrap property doesn't seem to work as expected. function for ...

Steps for accessing the controller scope from a directive nested within another directive:

I am in the process of developing code that is as generic as possible. Currently, I have 2 directives nested within each other, and I want the inner directive to call a method on the main controller's $scope. However, it seems to be requesting the m ...

Scroll with Angular to Move Elements

Is there a way to convert this Jquery Code into an angularJs directive? http://jsfiddle.net/MMZ2h/4/ var lastScrollTop = 0; $("div").scroll(function (event) { var st = $(this).scrollTop(); if (st > lastScrollTop) { $('img').a ...

Can you provide me with information on how to retrieve data from a Yahoo Finance JSON file using Node.js?

I have created a simple request function to fetch JSON data from the Yahoo Finance API, but I am encountering difficulties in extracting information from the JSON response. Here is my code: var request = require("request"); var stock_url = "http://finan ...

Another option instead of using $index for displaying serial numbers in ng-repeat

Looking to display a serial number for each table data entry being generated through the use of ng-repeat. The current code I have is as follows: <tr ng-repeat="usageRecord in applicationUsageDataForReport"> <td style="text-align: center">&l ...

Provide input to npm when running "my command" and utilize that input within my functions

Consider the contents of app.js const { doCoolStuff } = require("./api/myApi"); // grab parameter from command line and store it in "myParam" doCoolStuff(myParam); ... // more code And Package.json: { "name": "------ ...

Is it essential to have the bootstrap4 column 12 DIV for optimal performance on mobile devices?

Is it necessary to use bootstrap4 DIV col-12 for mobile devices? Even if a DIV takes up full width on mobile without col-12, why is it still recommended to include it? ...