Detecting unutilized space in a collection of divs with varying sizes using JavaScript and CSS

To better understand my issue, I created a StackBlitz demo: https://stackblitz.com/edit/angular-aqmahw?file=src/app/tiles-example.css

Screenshot

My tiles can have four different widths (25%, 50%, 75%, 100%).

The tiles must fit on only two lines, so if all the tiles are 25% wide, there can be up to 8 of them.

I'm currently looking for an algorithm that can identify the empty spaces on these two lines and determine their sizes. This way, when adding a tile, I want it to fill in these empty spaces rather than just appending it to the end of the list.

Could anyone assist me with developing this algorithm?

Answer №1

* {
  box-sizing: border-box;
}

.example-list {
  --columns: 4;
  --gap: calc(8 / 16 * 1rem);
  display: grid;
  grid-template-columns: repeat(var(--columns), 1fr);
  grid-template-rows: masonry;
  gap: var(--gap);
}

.example-box {
  background: rgba(0, 0, 0, 0.25);
  height: 200px;
  border-radius: var(--gap);
  padding: var(--gap);
}

.example-box span {
  display: flex;
  justify-content: center;
  align-items: center;
}

.size-1 {
  grid-column: span 1 / auto;
}

.size-2 {
  grid-column: span 2 / auto;
}

.size-3 {
  grid-column: span 3 / auto;
}

.size-4 {
  grid-column: span 4 / auto;
}
<div _ngcontent-htr-c99="" class="example-list">
  <div _ngcontent-htr-c99="" class="example-box size-1"></div>
  <div _ngcontent-htr-c99="" class="example-box size-1"></div>
  <div _ngcontent-htr-c99="" class="example-box size-2"></div>
  <div _ngcontent-htr-c99="" class="example-box size-1"></div>
  <div _ngcontent-htr-c99="" class="example-box size-2"></div>
  <div _ngcontent-htr-c99="" class="example-box size-1"></div>
  <div _ngcontent-htr-c99="" class="example-box size-3"></div>
  <div _ngcontent-htr-c99="" class="example-box size-1"></div>
  <div _ngcontent-htr-c99="" class="example-box size-4"></div>
  <!--bindings={
  "ng-reflect-ng-for-of": "[object Object],[object Object"
}-->
</div>

It is recommended to utilize grid for better control over 2D space instead of using flex for 1D space

I have reconstructed your example on this platform https://stackblitz.com/edit/angular-teylho?file=src/app/tiles-example.ts

Answer №2

Alright, here's my solution: https://stackblitz.com/edit/angular-n6dqoj?file=src%2Fapp%2Ftiles-example.ts

In addition to your original tiles object, I have added variables that allow for dynamic changes:

  • Total size allowed per row (maximumSizePerRow),
  • Number of rows you desire (maximumNumberOfRows),
  • Beginning name of each row (rowPrefix) for display and logging purposes.

I also incorporated two arrays containing information about the rows' content, used for adding new tiles:

  • rowsData stores data on each row (name, available spaces, tile names),
  • tilesUsed includes only the tiles to be displayed based on desired number of rows. These replace the original tiles in the template.

The algorithm is straightforward: after setting up the structure of rowsData, the code loops through each row, then through each tile from the tiles object. If conditions are met - such as enough space in the row or tile not being used elsewhere - the tile is placed in the row. This ensures that only tiles fitting within the specified criteria are displayed.

The view will show only the tiles within the allocated rows, with a final console log providing details on remaining empty spaces per row.

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

Bootstrap is unable to function properly without jQuery, throwing an error message that states: "Bootstrap's JavaScript

Attempting to create a Bootstrap interface for a program. Added jQuery 1.11.0 to the <head> tag, however upon launching the web page in a browser, jQuery throws an error: Uncaught Error: Bootstrap's JavaScript requires jQuery Various attempts ...

Experimenting with Cesium using Jasmine (Angular TypeScript)

I have a TypeScript app built using Angular that incorporates Cesium: cesium-container.component.ts import { Component, ElementRef } from '@angular/core'; import { Viewer } from 'cesium'; import { SomeOtherCesiumService } from 'sr ...

What is the best way to ensure that less2css compiles all files after saving just one less file?

In my project, I have a style.less file that imports "page.less". Whenever there is a change made to page.less, I find myself having to go back to the style.less file and save it in order for less2css to compile and apply the changes. If not, the changes ...

JS: Submitting form data through POST method but fetching it with GET method?

When using PHP to retrieve data, the $_POST method cannot be used; only $_GET. Why is that? Could it be that I am not sending my form data correctly? I assumed that by using request.open("POST"), the form would be processed as a POST request rather than a ...

Extracting information from a JSON data within an API

How can I retrieve data with a name tag from JSON data using Ajax? The function showCard is not functioning properly when I try to grab data with a name tag. My goal is to display the name of the API data when an img element with the class found is clicked ...

Adding animation to a div that is being appended can be done by using JavaScript functions and

I am looking to incorporate animation into my title div. Below is the HTML code I have so far: <div class="particles" id="tittle"> <!-- Displaying title from Firestore using JavaScript --> </div> Here is the CSS cod ...

Searching for identical consecutive numbers in a grid

Hi there, I'm currently working on developing a function that can detect if a N*N matrix contains at least two adjacent numbers (ranging from 0 to h-1) in the up-down-left-right directions. The function should return 1 if such numbers are found, and 0 ...

Issue with Electron: parent window not being recognized in dialog.showMessageBox() causing modal functionality to fail

Struggling with the basics of Electron, I can't seem to make a dialog box modal no matter what technique I try. Every attempt I make ends in failure - either the dialog box isn't modal, or it's totally empty (...and still not modal). const ...

What exactly is the purpose of measuring "First Load JS" in the @next/bundle-analyzer tool?

The analysis generated by the NextJS bundle analyzer appears as follows: Page Size First Load JS ┌ λ / 12 ...

Executing ng test and ng serve at the same time

As someone who is still learning Angular 5, I am in the process of setting up a development environment for my team to work on a new Angular 5 application. My goal is to have our team able to run linting tests and unit tests every time they make changes, ...

Creating an expandable discussion area (part II)

After checking out this query that was posted earlier, I am interested in implementing a similar feature using AJAX to load the comment box without having to refresh the entire page. My platform of choice is Google App Engine with Python as the primary lan ...

Bootstrap 5 NavBar Toggle hamburger Menu not displaying menu items

I attempted to create a navigation bar using the navbar instructions in Bootstrap 5. I included a Toggle hamburger Menu and linked it to the list that should be displayed. However, when I decrease the screen size, the Toggle feature does not function as ex ...

What is the process for requesting a css file?

My CSS file is pretty lengthy, with over 3000 lines (yes, it's a tad excessive). I'm looking to organize them in alphabetical order so I can easily locate properties. Using Ctrl+F simply tires me out because of the abundance of similar selectors. ...

How about this: "Looking to Share on Social Media with ME

After developing an app using MEAN.js, I made enhancements to the Articles (blog) section to improve SEO, readability, and design. However, one issue I'm struggling with is how to properly share these Articles on social media platforms like Facebook, ...

What is the importance of accessing the session object prior to the saving and setting of a cookie by Express-Session?

Quick Summary: Why is it crucial to access the session object? app.use((req, res, next) => { req.session.init = "init"; next(); }); ...in the app.js file after implementing the session middleware for it to properly function? Neglecti ...

Modifying the calendar from a 7-day week to a 5-day week

I am currently in the process of developing a 7-day calendar (Sunday to Saturday) which is functioning well. However, I am interested in adding an option to switch it to a 5-day calendar (Monday to Friday). I was wondering if there is a way to modify the e ...

"Why does the React useState array start off empty when the app loads, but then gets filled when I make edits to the code

I'm facing a challenging task of creating a React card grid with a filter. The data is fetched from an API I developed on MySQL AWS. Each card has a .tags property in JSON format, containing an array of tags associated with it. In App.jsx, I wrote Jav ...

No control access origin header found on the request to Spring 5 WebFlux functional endpoints

I have scoured numerous resources in search of the perfect solution to my issue. In my opinion, I believe I have all the necessary components in place but I am unable to pinpoint where the problem lies. Utilizing spring 5 with WebFlux and functional endpo ...

Changing the dropdown value by clicking the previous and next buttons in Angular 2

I need to implement a feature in Angular 2 where the default date displayed in a dropdown is the current year. Additionally, when the "Prev" button is clicked, the selected year value in the dropdown should decrease by one. // Our root app component imp ...

How can I utilize Luxon to calculate the total number of days that are equal to or greater than 30?

Looking at my current array structure const arr = [ { id: '1', name: 'thing1', createdAt: '2022-09-21T16:26:02Z', }, { id: '2', name: 'thing1', createdAt: '2022-11-21T16:20:20Z', } ...