Determine the maximum size of a specified number of square divs that can fit within responsive parent divs

I am working on creating a grid of square divs inside a container with variable height and width.

The number of square div's is predetermined. All square divs will have images with the same dimensions (similar to the example). They should align left and wrap around at the end of one row to the next. I need an algorithm to calculate the number of columns, rows, and their maximum size to fit them all into the parent div.

Can someone provide me with a suggestion on how to determine the maximum size of the squares so that each square fits within the parent container? It seems like I am facing a packing problem here.

The current code I am using to calculate the image height is:

var imageHeight = Math.floor((maxHeight - imageMargin) / 3);

For more detailed code, you can check out this working example on JSFiddle

var $container = $('.container');
var $square = $('.square');

adjustSquares();
function adjustSquares() {
// CALCULATE MAXIMUM CONTAINER HEIGHT (for instance, half of window height)
  $container.removeAttr('style');
  var maxHeight = Math.floor($(window).height() / 2);
  $container.css({
    'max-height': maxHeight + 'px',
    'overflow': 'hidden'
  });

  // CALCULATE MAXIMUM IMAGE HEIGHT (based on the number of squares and the maximum container height)
  var imageMargin = $square.outerWidth(true) - $square.width();
  var imageHeight = Math.floor((maxHeight - imageMargin) / 3); // How to calculate this image height?
  $square.find('img').width(imageHeight);
  $square.find('img').height(imageHeight);

  // CALCULATE CONTAINER WIDTH (to determine the maximum number of squares per row and center them)
  var maxWidth = $container.width();
  var blockWidth = $square.outerWidth(true);
  var squaresPerRow = Math.floor(maxWidth / blockWidth);
  $container.width(squaresPerRow * blockWidth);
}

var resizeTimeout;
$(window).resize(function() {
clearTimeout(resizeTimeout);
  resizeTimeout = setTimeout(adjustSquares, 200);
});
body {
  padding: 0;
  margin: 0;
}

.container {
  width: 100%;
  margin: 0 auto;
  font-size: 0; /* REMOVE inline-block SPACE */
}

.square {
  display: inline-block;
  margin: 5px;
}

img {
  max-width: 100%;
  height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="container">
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
    <div class="square">
      <img src="http://lorempixel.com/100/100" alt="square" />
    </div>
  </div>
</body>

Answer №1

To properly adjust the height of all elements with the class .square, you will need to iterate through each of them using the $.each() function.

$(function () {
  var tallestHeight = 0;
  $(".square").each(function () {
    var currentHeight = $(this).height();
    tallestHeight = (currentHeight > tallestHeight) ? currentHeight : tallestHeight;
  });
  $(".square").css("height", tallestHeight);
});

Answer №2

Hooray, I did it!

After referencing this helpful post on Math Stackexchange, I was able to find a practical solution.

The step-by-step process I followed:

  var containerWidth = $container.width();
  var containerHeight = Math.floor($(window).height() / 2);

  $container.css({
    'max-height': containerHeight + 'px',
    'overflow': 'hidden'
  });

  // DETERMINING MAXIMUM SQUARE SIZE based on the number of squares and the dimensions of the container
  var hw = containerHeight / containerWidth;
  var wh = containerWidth / containerHeight;

  var px = Math.ceil(Math.sqrt(squareCount * hw));
  var py = Math.ceil(Math.sqrt(squareCount * wh));

  var sx;
  if (Math.floor(px * wh) * px < squareCount) {
    sx = containerWidth / Math.ceil(px * wh);
  }
  else {
    sx = containerHeight / px;
  }

  var sy;
  if (Math.floor(py * hw) * py < squareCount) {
    sy = containerHeight / Math.ceil(py * hw);
  }
  else {
    sy = containerWidth / py;
  }

  var squareDimension = Math.floor(Math.max(sx, sy) - squareMargin);
  $squares.find('img').width(squareDimension);
  $squares.find('img').height(squareDimension);

Take a look at this demo link to see the updated calculation algorithm in action.

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

Vue components failing to reflect code changes and update accordingly

Initially, the component functions properly, but subsequent changes require me to restart the server in order to see any updates. ...

What causes ngClick to stop working following $compile?

http://plnkr.co/edit/kL2uLPQu2vHHKIvRuLPp?p=preview Upon button click, the controller calls a service to compile HTML and inject it into the body. The compiled HTML (displaying "Hello World" from $scope.name) is referring to the scope of the controller, ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

Is there a way for my React application to detect changes in an npm package?

I am currently customizing an npm package for my application, but I am facing issues with it not being detected when starting my development server. Previously, I was able to resolve this by removing the library and reinstalling it, followed by replacing t ...

Avoiding layout shift when a button is clicked in React JS

I am working on a Drawer example and following the instructions provided at https://mui.com/material-ui/react-drawer/ Everything is functioning as expected, but I am encountering an issue where my content shifts to the right when the drawer opens, and ret ...

Is there a node.js equivalent to Turbolinks available?

One of my favorite features in Rails is Turbolinks, as it enhances the user experience by making pages appear to load faster. Is there any alternative or similar functionality for node.js? ...

JavaScript code that iterates through all files in a designated folder and its subfolders using a for loop

I am looking to combine two JavaScript scripts into one, but I'm not sure how to do it. The first script uploads files from a specified folder to VirusTotal for scanning and returns the scan result. The second script lists all files in the specified ...

What is the best way to utilize an onClick on a button to update a value that is being utilized in a useEffect hook?

I am looking for a way to dynamically change the content displayed in this section without navigating to another page. I have two sets of data - one displaying all blogs and the other showing only blogs authored by "mario". How can I implement a button cli ...

I recently created a Python3 script utilizing selenium to automate message sending, but unfortunately, it is not functioning as expected

I've written a script (https://pastebin.com/dWLFvirn) that I'm trying to run through the terminal, but it's giving me an error. Here's a screenshot of the error (https://ibb.co/NSfLgL8). I would like to use "" as the link to make the s ...

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

Utilizing AngularJS: Transforming JSONP information into HTML

I'm relatively new to utilizing $http and fetching data from various websites. My main query is, how can I convert JSONP into HTML? Specifically, when using $http to request the Atari Wikipedia page, the content is displayed with and HTML elements. ...

Achieving Perfect Alignment of Images Using HTML and CSS

I am currently working on designing a HTML/CSS layout for a Kiosk-style website. However, I am encountering some challenges in getting the alignment of images and text to appear exactly as desired. The goal is to have the logo and header remain fixed in ...

Retrieve JSON data within a service and provide it to a component

I am currently facing an issue with loading data from a JSON file into my component using a service. The data is successfully loaded in the service, as confirmed by the console log; however, when trying to access the data in the component, it does not disp ...

SyntaxError in ExpressJS: Encountered an unexpected token "C"

I'm having trouble saving my string to a comma-separated array. When I attempt to use the JSON.parse method, I encounter an error while sending a post request and trying to save a record: SyntaxError: Unexpected token c at Object.parse (native) ...

JavaScript: A guide on sending an uploaded email to a web service in byte array format

Scenario: My website is built using EXTJS6. I have a web service that requires the uploaded email to be sent in byte array format. Inquiry: What is the process for converting a .msg file to a byte array using JS (or EXTJS)? Can we treat it as a simple bin ...

The lack of flexibility in this element stems from the fact that it is not classified as a flex item

I'm facing an issue with flexbox and its unusual behavior. I have set up flexbox for the parent element and used flex: 1 1 100%, but it's not working as expected. When I checked in Firefox Developer Tools, it says that the parent is not a flex co ...

Effects of jQuery Show / Hide on adjacent select box operations

I created a pair of select boxes where the visibility of one is controlled by the other. Initially, the controlled select box (#select02) works perfectly on page load as long as I don't show/hide it by selecting options in the controlling select box ( ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Does Node.js support backward compatibility?

There is a common belief that Node.js is backwards compatible, meaning scripts running in Node.js N should also work in Node.js N+1. I have been unable to find any documentation confirming this assumption. Is there another way to verify compatibility aside ...

Navigating Divs Using jQuery

I am working with a class that has multiple divs, each with a unique id attached to it. I am using jQuery to dynamically cycle through these divs. This is a snippet of my HTML code: <div id ="result">RESULT GOES HERE</div> ...