Ensuring child divs maintain set proportions within parent div

I am looking to develop a jQuery/javascript function that dynamically populates a parent div with child divs of varying sizes, collectively taking up the size of the parent container.

For instance, envisioning 10 child divs filling a container div sized at 1200px x 600px

<div class="container">
   <!-- Insert 10 child divs here with unique dimensions. -->
</div>

Answer №1

A helpful approach is to use a function that divides a rectangle into two subrectangles, and then recursively splits those subrectangles.

  • When dividing a rectangle into two parts with an even number N of subrectangles, each part will have N/2 subrectangles.
  • If a rectangle is split into two parts with an odd number of leaf subrectangles, the larger part will have one more child than the smaller part.

function fillWithChilds(el, N) {
  function rand(n) {
    /* weight=100 means no random
       weight=0 means totally random  */
    var weight = 50;
    return Math.floor(weight*n/2+n*(100-weight)*Math.random())/100;
  }
  function main(N, x, y, hei, wid) {
    if(N < 1) return;
    if(N === 1) {
      var child = document.createElement('div');
      child.className = 'child';
      child.style.left = x + 'px';
      child.style.top = y + 'px';
      child.style.width = wid + 'px';
      child.style.height = hei + 'px';
      el.appendChild(child);
      return;
    }
    var halfN = Math.floor(N/2);
    if(wid > hei) {
      var newWid = rand(wid);
      if(2*newWid > wid) halfN = N-halfN;
      main(halfN, x, y, hei, newWid);
      main(N-halfN, x+newWid, y, hei, wid-newWid);
    } else {
      var newHei = rand(hei);
      if(2*newHei > hei) halfN = N-halfN;
      main(halfN, x, y, newHei, wid);
      main(N-halfN, x, y+newHei, hei-newHei, wid);
    }
  }
  main(N, 0, 0, el.clientHeight, el.clientWidth);
}
fillWithChilds(document.getElementById('wrapper'), 11);
#wrapper {
  background: #ccf;
  position: relative;
  height: 300px;
  width: 400px
}
.child {
  background: #cfc;
  outline: 2px solid red;
  position: absolute;
}
<div id="wrapper"></div>

Answer №2

Finding a solution for distribution may be challenging. Perhaps there is a jQuery library that can assist with some aspects of it... I will investigate further. Despite the complexity, solving this problem is quite enjoyable.

Here is my current progress, although it is somewhat brief.

http://jsfiddle.net/twPQ7/2/

The section that calculates how many additional components need to be built is the tricky part. I am aiming to minimize the number of loops in this process:

var containerSize = getContainerSize();
var elementWidth = 0;
var elementHeight = 0;

// calculating width
while (elementWidth < containerSize.x)
{
    var size = generateElement();
    elementWidth += size.x;
    elementHeight += size.y;        
}
// adjusting height if necessary
while (elementHeight < containerSize.y)
{
    var size = generateElement();
    elementWidth += size.x;
    elementHeight += size.y; 
}

I have made some improvements. Please review the updated fiddle: http://jsfiddle.net/twPQ7/2/

// determining container size
var containerSize = getContainerSize();
var elementWidth = 0;
var elementHeight = 0;

// generating elements iteratively until reaching container width
while (elementWidth < containerSize.x)
{
    var size = generateElement();
    elementWidth += size.x;

    // keeping track of the tallest element.
    if (size.y > elementHeight) elementHeight = size.y;
}
// generating elements iteratively until reaching container height
while (elementHeight < containerSize.y)
{
    var size = generateElement();
    elementHeight += size.y; 
}

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

Eliminate specific elements from an array while retaining others

Here is a simple page setup: https://i.sstatic.net/z9MF9.png The page consists of an input field at the top, followed by a list (<ul>), and a button for saving changes. The <ul> is connected to an array called items. When the user clicks on "S ...

Dropdown for state selection within WooCommerce for specific countries

I am encountering a challenge in configuring a form with default WooCommerce country and states selection dropdowns. Essentially, my goal is to present the Country selection first, followed by the State selection based on the chosen country. For instance, ...

Making a jQuery post request that returns JSON data

Is it possible to use the jQuery $.ajax method for making a POST request and sending data (e.g. page.aspx?var1=value) while also specifying that the expected response from the service will be in JSON format? var data = {name: _name, ...}; var request = $ ...

Unexpected symbol in JSON parsing with JavaScript

let information; $.ajax({ url: link, type: 'POST', dataType: "json", success: function (data, textStatus) { information = data; alert(data.name); } }); I am attempting to retrieve JSON-encoded data from a spe ...

Encountering problems with displaying the quantity on WordPress archive pages

I recently attempted to enhance a WordPress webshop I am developing by adding a quantity field. My goal was to allow customers to add products to their cart directly from the archive page, instead of having to navigate to the individual product pages. To ...

Vessel + AngularJS - CORS rejection in action

Snippet: @route('/characteristicsToBestWeb', method='OPTIONS') def respondToCharToBestQueryWebOptions(): response.headers['Access-Control-Allow-Origin'] = settings.allowed_web_origin response.headers['Access-Cont ...

Is there a way to turn multiple lines of text into a tooltip label that appears when hovered over?

My goal is to have underlined text that spans multiple lines and reveals a tooltip when hovered over. I've managed to include multiple lines in the tooltips, but I'm struggling with applying the labels correctly. I am completely new to HTML; I r ...

Utilizing AJAX for Client-Side Updates in PagedList Functionality

I am currently working on an MVC application that utilizes PagedList for paging. One of the requirements is to have a checkbox in the first column and allow users to select rows and have those selections preserved throughout the paging process. For examp ...

What are some effective design principles for creating REST APIs in expressjs?

To streamline my code organization, I made the decision to create a methods folder. Within this folder, I store individual JavaScript files for each URL endpoint (such as website.com/billings). //expressJS configuration... const billings = require('. ...

Angular 2 can efficiently generate multiple HTTP requests simultaneously from a single HTTP request

Backend API's: url: [ { "name": "ABC", "occupation": "Student", "address_url": "http://www.sample.com/address/person=hgjgjgyyfhg" }, { "name": "ABC1", "occupation": "Carpenter", "address ...

Changes in content result in modifications to the size of transition elements

Have you ever encountered a button with changing text upon being pressed? The transition in text leads to a shift in the button's width. Wouldn't it be amazing if one could smoothly transition the change in width of an element using a code snippe ...

Transform the javascript ES6 class into a functional programming approach

I am interested in converting my reactjs class to a functional programming approach rather than using OOP. Can anyone provide guidance on how to achieve this? Please refer to my code snippet below. import * as h from './hydraulic'; const vertic ...

Customizing popups and tooltips in Material-UI charts

Has anyone had success with customizing the appearance of the popover/tooltip in mui charts? It seems like it should be a simple task, but despite searching extensively, I have only found information on formatting data and nothing about styling the CSS. ...

Using JQuery .ajax to store information in the database

I'm in the process of saving 2 different pieces of information into the database using JQuery and the .ajax function. Specifically, I need to save the postID and the userID in a WordPress environment. While I have a good understanding of most of the f ...

Differences in Appearance of Bootstrap .btn in Safari Browser

Looking for help with my HTML code: <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <a href="poweron.php" type=" ...

Ways to merge multiple cells horizontally in a table right from the beginning

Is there a way to start the colspan from the second column (Name)? See image below for reference: https://i.stack.imgur.com/RvX92.png <table width="100%"> <thead style="background-color: lightgray;"> <tr> <td style="width ...

If the variable is not defined, then utilize a different one

There are two scopes: $scope.job and $scope.jobs. I also have a variable called job; If $scope.job is undefined, I want $scope.jobs to be assigned to the job variable using the following code: var job = $scope.jobs. However, if $scope.job is defined, the ...

Tips for verifying conditional input fields in a React component?

As a beginner in React, I attempted to create a SignIn form component that dynamically changes its layout based on a boolean prop toggled between Login and Signup options. In the signup version, there is an additional text field labeled Confirm password, w ...

Explore through descendant elements and locate attributes (up to a specified number of levels)

Consider the JSON data below: var responseData = { "Status": "Met", "Text": "Text1", "Id": "AAA", "ContentItems": [ { "Selected": true, "Text": "Text2", "Id": "BBB" }, { "Status": "Met", "Text": "Text3", ...

Issue with jQuery, Ajax, and Haml as js.erb files are not triggering

After researching various sources, it seems like this issue needs to be addressed once more. When coding in Rails3, I am attempting to incorporate smooth Ajax effects when a user attempts to create a post on a different element of my application. Here&apos ...