Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated.

https://i.sstatic.net/vBtXc.png

When there are more than 9 items, the current layout changes the order from top to bottom. Is there a solution to maintain the desired item placement?

    private getKeysStyle(items: string) {
    if(items.length >= 9){
        return {
            marginTop: '8px',
            display: 'grid',
            gridGap: '6px',
            gridAutoFlow: 'column',
            gridTemplateColumns: 'repeat(auto-fill, minmax(40px,1fr))',
            gridTemplateRows: 'repeat(4, 1fr)',
        };
    }
    return {
        marginTop: '8px',
        display: 'grid',
        gridGap: '6px',
        gridTemplateColumns: 'repeat(2, 1fr)',
    }
}

The current sorting order is not meeting the requirement. I need to adjust the order accordingly.

https://i.sstatic.net/537EI.png

Answer №1

To achieve this effect using only CSS, one can utilize the nth-child selector:

.container {
  display:inline-grid;
  counter-reset:num;
  grid-template-columns:50px 50px;
  grid-auto-columns:50px;
  margin:5px;
}

/* create another column after 9 elements */
.container > :nth-last-child(9) ~ :nth-child(3),
.container > :nth-last-child(11) ~ :nth-child(3){
 grid-column:3;
}

/* create another column after 12 elements */
.container > :nth-last-child(13) ~ :nth-child(4), 
.container > :nth-last-child(16) ~ :nth-child(4){ 
 grid-column:4;
}

/* create another column after 16 elements */
.container > :nth-last-child(17) ~ :nth-child(5),
.container > :nth-last-child(21) ~ :nth-child(5), 
.container > :nth-last-child(25) ~ :nth-child(5){ 
 grid-column:5;
}



.container div {
  padding:10px;
  outline:1px solid;
}
.container div::before {
  content:counter(num);
  counter-increment:num;
}
<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>


<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

<div class="container">
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>

Answer №2

Based on the given description, if you want to limit the number of rows to four when there are nine or more items and have columns generated automatically, a bit of numeric manipulation is required.

private getKeysStyle(items: string) {
  if (items.length >= 9) {
    // Calculate the number of columns needed while keeping rows restricted to 4.
    const columnCount = Math.ceil(items.length / 4);

    return {
        marginTop: '8px',
        display: 'grid',
        gridGap: '6px',
        gridAutoFlow: 'column',
        gridTemplateColumns: `repeat(${columnCount}, minmax(40px, 1fr))`,
        gridTemplateRows: 'repeat(4, 1fr)',
    };
  }

  return {
    marginTop: '8px',
    display: 'grid',
    gridGap: '6px',
    gridTemplateColumns: 'repeat(2, 1fr)',
  }
}

To make the grid place items column-wise and move to the next row after each column in the previous row is filled, remove auto-fill and specify explicit columns.

Updates: When the length exceeds 9, remember to include the property grid-auto-flow: column; in the styles object. By default, it operates row-wise, filling up all columns in one row before moving to the next. Setting it to column changes this behavior to fill columns first before advancing to the next.

Explore more about grid-auto-flow here.

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

Using NGRX Effects to Load Data for a Specific Item in Angular

On my website, there is a page that displays a range of products from the store managed by a reducer called products. When an action PRODUCTS.LOAD_ALL is dispatched, it triggers an API call through an effect and then sends a PRODUCTS.LOAD_ALL_SUCCESS actio ...

`There are two text boxes in a blog post editor within tinyMCE`

I'm currently working on building a blog app using Django. The issue I'm facing is related to the Tinymce editor in the post creation form. Everything works perfectly fine except for one annoying element that shows up within the text box itself. ...

The AJAX success function is operational, yet the file does not execute

As a newcomer to StackOverflow and web development, I am pressed for time with this assignment, so please bear with me if I struggle with understanding web development terminologies. My current challenge involves calling another php file through ajax in my ...

Verify if the value in a textbox exceeds the number entered in an array of textboxes

My goal is to compare the value of a single text box, labeled as "totalmarkstoall", with multiple arrays of text boxes labeled as "marksscored". The JavaScript code below is set up to compare these values using a key up function. The issue I am facing is ...

Designing a responsive two-column table layout

My current challenge involves a small table structured as a bullet list with two columns. To enhance mobile display, I am seeking a way to collapse it down to a single column: The current implementation includes the following code snippet: <style> @ ...

Unusual actions observed in ajax rails form calculator with pre-filled values

I have a form calculator in Rails that utilizes AJAX without a database. While it functions properly, I have noticed some peculiar behavior which I would like to address. Firstly, I navigate to the /interest_calculator page Then, I input 10 into @first_0 ...

substituting the deep watcher in Angular

In my application, I am working with a data object called fulldata, which consists of an array of objects. fulldata = [ {'key': 'abc', values: {.....},....}, {'key': 'efg', values: ...

Initialization of Masonry JS occurs prior to images being fully loaded

I am in the process of creating a website to serve as my portfolio for university applications. Despite my efforts, I am struggling with the javascript aspect and have not been successful in resolving the issue by following similar inquiries. The problem ...

What is the best way to modify the selection text background with CSS?

Does anyone know the method for modifying the selection text background in CSS? Many modern websites opt for a personalized background color instead of the traditional blue? ...

Dividing the code into a function and invoking it does not produce the desired outcome

Everything seemed to be working perfectly until I attempted to encapsulate the code into a function and call it within my expression. Unfortunately, this approach did not yield the desired results. Functional code: render: function() { return ( ...

Using Grails to create remote functions with multiple parameters

Currently, I am able to send one parameter to the controller using the code snippet below in Javascript: <g:javascript> var sel = "test"; <g:remoteFunction action="newExisting" method="GET" update="updateThis" params="'sel='+s ...

Having difficulty utilizing the $.each() function to assign properties to an object

I have an object called habits that contains some values. var habits={ "Drinking":"No", "Smoking":"No" } I want to add the values from this variable into another variable in the following format: var NewHabits = new Object(); Ne ...

How can I locate specific images within a CSS sprite?

Are you searching for the correct process to pinpoint specific image locations within an image sprite? If, for example, you aim to create 10 div images in your header using the image provided below, how can you determine the exact location of each one? Is ...

I prefer not to have the entire URL visible to me

function updateDate(day, month, year) { month += ""; if (month.length <= 1) month = "0" + month; document.location.href = "<?php $_SERVER['PHP_SELF'];?>?page=events&day=" + day + "&month=" + m ...

Utilize a unique font exclusively for Internet Explorer

I am encountering a significant issue trying to utilize custom fonts in Internet Explorer. Currently, I have implemented a specific font using @font-face and it works perfectly in modern browsers but fails to render properly in IE. The method I am curren ...

Struggling with the task of assigning a glTF item to a separate layer within Three.js

Exploring the use of layers in Three.js. This script includes a sphere, a triangle, and a glTF object (car). I activated a second layer: camera.layers.enable(1); Assigned the sphere, triangle, and glTF object to layer 1: car.layers.set( 1 ); sphere.lay ...

Generate random div elements and insert them dynamically into a fixed-sized container using AngularJS. The number of div elements created can range anywhere from 0 to

Within a div of fixed size, dynamically generated div elements are displayed using ng-repeat. The inner divs should adjust their size to accommodate the number of child divs present - for example, if only one div is present, it should take up 100% of the s ...

What is the method for placing one object within another object?

This is a sample of my data collection: [ { "column1":"data1", "column2":"data2", "column3":[ { "column31":"data31", "column32& ...

Is it possible to load a route first, and then proceed to load the static files from the public folder in a Node.js application?

When running the app.js file for Node.js, I am trying to ensure that the '/' route is loaded first. This route handles authentication and then redirects to the index.html file. However, I am encountering an error because the program cannot find ...

What is the best way to automatically add a date and timestamp to every new entry?

I am currently working on a project that utilizes AngularJS and Ionic frameworks. The main feature of the project will involve users inputting data to create a list, and allowing any user to comment on each item in the list. One challenge I have encounter ...