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.

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.

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

Guide on updating the state using a computed property in Vue.js

I'm facing an issue with updating my state data within a computed property named computedFirstName. Currently, the state changes on every letter I type, but I only want it to update when I click the submit button and call the update method. Below is ...

Create independent SVG files using Meteor and iron-router

My goal is to use Meteor and Iron-Router to serve dynamic SVG files with templating capabilities. To start, I create a new route: @route 'svg', { path: '/svg/:name' data: -> { name: this.params.name } # sample data layoutT ...

TS1086: Attempting to declare an accessor within an ambient context is not allowed

While using Angular, I encountered the error TS1086: An accessor cannot be declared in an ambient context. when using Javascript getters and setters in this Abstract Typescript class. Here is the code snippet causing the issue: /** * The current id ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

Unusual express middleware usage in NodeJS

app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.get('/2',function(req,res){ console.log('/2'); res.end() ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

Angular JS may encounter a cross domain problem when attempting to post on a third-party website

HTML Code: <div ng-app="myApp" ng-controller="myController"> <div> <input type="button" data-ng-click="submit()" ...

Instructions on how to create a horizontal scrolling div using the mouse scroll wheel

I need help with scrolling a div horizontally using the mouse scroll button. My div does not have a vertical scroll and I would like users to be able to scroll horizontally. Can anyone provide guidance on how to achieve this? ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

Display/Modify HTML form

Looking for advice on how to create an interactive HTML form that displays data and allows users to edit it by clicking 'Edit' before submitting changes. Any suggestions on how to implement this functionality? ...

Deciphering HTML with the Eyes

So, I find myself in a bit of a bind trying to come up with a title for this question. I have stumbled upon some HTML files that seem so complex, they could only have been crafted by the one and only Lord Lucifer himself. These files contain segments like ...

Issue with uploading files in Internet Explorer using Ajax not resolved

I've been encountering an issue while uploading images using Ajax and PHP. Surprisingly, everything runs smoothly on Firefox but fails to work on Internet Explorer (I.E). Take a look at my HTML code below: <!doctype html> <head> <titl ...

Jquery is causing some issues with the code provided:

This is the code snippet from script.js: $(document).ready(function() { $('#mainobject').fadeOut('slow'); }); Here is a glimpse of index.html: <!DOCTYPE html> <html> <head> <title>Hitler Map&l ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

What is the best way to incorporate CSS into this HTML document?

Content has been omitted. It is crucial to review documentation in advance in order to reduce repetitive inquiries. Check out the Webpack v2 documentation. ...

What is the accurate way to write the ID selector for the select-option-selected in JQuery?

When it comes to extracting a value from a Select-Option using jQuery, the following syntax can be used. I have successfully retrieved data using this method. $( "#Vienna\\.rail0\\.track option:selected" ).text() However, there is an ...

Saving data in a CSV file on your local device using HTML5

Is it possible to utilize HTML5 for saving or writing data to a local file on the user's file system? I am curious about this functionality, especially since HTML5 now offers the capability to export data from the client and save it as a CSV file. If ...

Invoke the componentDidMount() method in a React Component that is not a subclass of React.Component

I have a react component that I render later in my index.js file index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <React.StrictMode> <App /> ...

Clicking activates Semantic UI's dropdown function with the onClick method

I am experiencing an issue with the dropdown functionality on my website. Everything works fine until I add onClick() to the Semantic UI component. It seems like there are some built-in functions for handling onClick() within Semantic UI, so when I impleme ...

Troubleshooting AngularJS: Diagnosing Issues with My Watch Functionality

I need to set up a watch on a variable in order to trigger a rest service call whenever its value changes and update the count. Below is the code snippet I have: function myController($scope, $http) { $scope.abc = abcValueFromOutsideOfMyController; ...