Is there a way to designate the order of layouts in a CSS grid?

Looking for some assistance with my grid layout on a specific section of a webpage. Here's how it's currently set up:

[1] [ Item 1 ] [2] [ Item 2 ]  
[3] [ Item 3 ] [4] [ Item 4 ]

When the screen size changes to mobile, it switches to this layout:

[1] [ Item 1 ]  
[2] [ Item 2 ]  
[3] [ Item 3 ]  
[4] [ Item 4 ]

However, I need the initial desktop view to be like this:

[1] [ Item 1 ] [3] [ Item 3 ]  
[2] [ Item 2 ] [4] [ Item 4 ]

The challenge arises because there are more grid items in the code and I want them to display in columns rather than rows. Adjusting the HTML order creates issues on mobile screens. I've explored grid-auto-flow but haven't found a solution yet. Any suggestions or guidance would be greatly appreciated!

.grid {
  display: grid;
  grid-template-columns: 48px 1fr 48px 1fr;
  column-gap: 12px;
  align-items: center;
  justify-content: center;
  background-color: orange;
  border: 1px solid black;
}

.grid-item {
  padding: 16px;
  border: 1px solid black;
  font-size: 12px;
  background-color: aliceblue;
}
<section class="grid">
  <div class="grid-item">1</div>
  <div class="grid-item">Item 1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">Item 2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">Item 3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">Item 4</div>
</section>

Answer №1

To rearrange the display sequence, you can utilize the order property ;)

You can achieve this by using the nth-child(n) selector in your HTML code as shown below:

.grid {
  display: grid;
  grid-template-columns: 48px 1fr 48px 1fr;
  column-gap: 12px;
  align-items: center;
  justify-content: center;
  background-color: orange;
  border: 1px solid black;
}

.grid-item {
  padding: 16px;
  border: 1px solid black;
  font-size: 12px;
  background-color: aliceblue;
}

.grid-item:nth-child(4n) ,/* catch 4, 8, ..*/
.grid-item:nth-child(4n - 1)/*, catch 3,7,...)*/
 {
  order: 1;
  color:green;
  font-weight:bold;
}
<section class="grid">
  <div class="grid-item">1</div>
  <div class="grid-item">Item 1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">Item 2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">Item 3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">Item 4</div>
</section>

Resources:

If the number of items is uncertain (and if there is a maximum possible known number), you can set up rules utilizing the :nth-last-child():first-child selector to distribute items into different columns based on the item count.

For instance, with 8 items (16):

.grid {
  display: grid;
  grid-template-columns: 48px 1fr 48px 1fr;
  column-gap: 12px;
  align-items: center;
  justify-content: center;
  background-color: orange;
  border: 1px solid black;
  grid-auto-flow:row dense;
}

.grid-item {
  padding: 16px;
  border: 1px solid black;
  font-size: 12px;
  background-color: aliceblue;
}

/* Fill first two columns */
.grid-item:nth-child(odd)  {
  grid-column:1;
}
.grid-item:nth-child(even)  {
  grid-column:2;
}

/* Separate odds and evens into respective columns for 8 items (16) */
.grid-item:nth-last-child(16):first-child~:nth-child(8) ~ .grid-item:nth-child(odd)  {
  grid-column:3;
}
.grid-item:nth-last-child(16):first-child~:nth-child(8) ~ .grid-item:nth-child(even)  {
  grid-column:4;
}
<section class="grid">
  <div class="grid-item">1</div>
  <div class="grid-item">Item 1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">Item 2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">Item 3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">Item 4</div>  
  <div class="grid-item">5</div>
  <div class="grid-item">Item 5</div>
  <div class="grid-item">6</div>
  <div class="grid-item">Item 6</div>
  <div class="grid-item">7</div>
  <div class="grid-item">Item 7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">Item 8</div>
</section>

In the previous snippet, you can adjust the rules by updating

.grid-item:nth-last-child(XX):first-child~:nth-child(X)
based on the number of child items being tested


Javascript can also be used to assign elements to specific columns easily.

let item = document.querySelectorAll(".grid-item");
i = 0;
let evenodd = (item.length/2)%2; // to make first col higher if amount of item not balanced
for (let e of document.querySelectorAll(".grid-item")) {
  i++;
  if (i >  item.length / 2 + evenodd ) {
    let pos = i;
    let odd = pos % 2;
    if (odd == 1) {
      e.classList.toggle("col3");
    } else {
      e.classList.toggle("col4");
    }
  }
}
.grid {
  display: grid;
  grid-template-columns: 48px 1fr 48px 1fr;
  column-gap: 12px;
  align-items: center;
  justify-content: center;
  background-color: orange;
  border: 1px solid black;
  grid-auto-flow: row dense;
}

.grid-item {
  padding: 16px;
  border: 1px solid black;
  font-size: 12px;
  background-color: aliceblue;
}

.grid-item:nth-child(odd) {
  grid-column: 1;
}

.grid-item:nth-child(even) {
  grid-column: 2;
}


/* Class assignment will be done through JavaScript */

.grid-item.col3 {
  grid-column: 3;
}

.grid-item.col4 {
  grid-column: 4;
}
<section class="grid">
  <div class="grid-item">1</div>
  <div class="grid-item">Item 1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">Item 2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">Item 3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">Item 4</div>
  <div class="grid-item">5</div>
  <div class="grid-item">Item 5</div>
  <div class="grid-item">6</div>
  <div class="grid-item">Item 6</div>
  <div class="grid-item">7</div>
  <div class="grid-item">Item 7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">Item 8</div>
  <div class="grid-item">9</div>
  <div class="grid-item">Item 9</div>
</section>

Answer №2

I have made some adjustments to your design to achieve the desired result. There are various ways to tackle this issue, and I've implemented my solution. I hope it suits your needs.

To summarize, I opted for using display flex instead of grid to create a layout with two columns (following a mobile-first approach) that stack on top of each other on smaller screens and switch to side by side on larger screens using media queries.

Below is the code snippet:

.flex {
  background-color: orange;
  border: 1px solid black;
}
.grid-item {
  padding: 16px;
  border: 1px solid black;
  font-size: 12px;
  background-color: aliceblue;
}
.row {
  display: flex;
  justify-content: start;
  align-items: center;
}
.row div {
  padding: 16px;
  border: 1px solid black;
  font-size: 12px;
  background-color: aliceblue;
  text-align: center;
}
.row .counter {
  max-width: 48px;
}
.row .item {
  flex: 1;
}

@media(min-width: 768px) {
  .flex {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .column {
    flex: 1;
  }
}
<section class="flex">
  <div class="column">
    <div class="row">
      <div class="counter">1</div>
      <div class="item">Item 1</div>
    </div>
    <div class="row">
      <div class="counter">2</div>
      <div class="item">Item 2</div>
    </div>
  </div>
  <div class="column">
    <div class="row">
      <div class="counter">3</div>
      <div class="item">Item 3</div>
    </div>
    <div class="row">
      <div class="counter">4</div>
      <div class="item">Item 4</div>
    </div>
  </div>
</section>

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

What is the best way to have every other row in a table expand to fill all of the cells?

My database log table contains information, and clicking a button reveals additional details about a specific log item. However, when the "info" button is clicked (refer to the image below), the displayed information only occupies the width of the "message ...

Iterate through Javascript quotes and automatically navigate to the first quote once the loop is completed

I've encountered an issue with the script where I am unable to loop back to the first element once all child elements have been traversed. https://jsfiddle.net/pad5bp0o/2/ Here is the jQuery code snippet: $(document).ready(function() { var length ...

I'm curious to know where in the CSS specifications it is specified how multiple properties with the same name should be handled

While debugging an unrelated issue, I want to make sure I understand how a browser is supposed to handle a declaration like background-image: url(image0.jpg); background-image: image-set(url(image1.jpg) 1x, url(image2.jpg) 2x); I tried looking in the CSS ...

Having trouble positioning the desired image at the bottom of the background using Tailwind CSS

I have been struggling to create a background with a video (z-index -2) and an image overlay (z-index -1). While I have managed to achieve this, I am having trouble getting the image to go all the way to the bottom where the footer is located. I am unsure ...

Modifying characters within a designated class definition

I'm working on integrating Isotope with a CuteNews system, and in order to make the filtering function properly, I need to include some identifiers in my class declaration for each isotope item. Link to Isotope In CuteNews, my news items can have mul ...

scss: creating variables dynamically using arrays

I am working on a dynamic way to generate different classes based on colors $colors: "dark" #3E3E3E, "darker" #3E3E3E, "light" #ECECF0, "green" #00A87B, "yellow" #FFBB3B, "red ...

Ensure that an input field on the PHP form is required

Currently working on a form with multiple input fields. I'm wondering if there's a way to prevent the form from being submitted to the server if a specific field is left empty. I'd like to use a JavaScript pop-up box to notify the user inst ...

Guide to Automatically Transform Markdown (.md) to HTML and Display it within a Designated <div> Container using Node.js alongside markdown-it Library

I am currently working on a unique project where my client specifically requires the ability to input Markdown (MD) content into a .md file and have it dynamically converted into HTML. The resulting HTML must then be displayed within a designated element i ...

The input focus placeholder at the top is not functioning properly when applied to an input field that

I recently designed an input box similar to this: https://i.stack.imgur.com/lkSnh.png However, I encountered an issue when trying to make the input box readonly. Here is a snippet of my code: .myinput input:focus { outline: none; } ... <div clas ...

Unable to establish the characteristic of 'undefined' to null while using React

For my application, I require the following functionality: If a question's value is null, then the checkbox should appear as indeterminate. Otherwise, it should be checked or not-checked accordingly. The issue arises when I try to update the questio ...

Encountering the error "undefined object" while using the yield keyword in JavaScript

var pi = document.getElementById("pi"); function * calculatePi(){ let q = 1; let r = 0; let t = 1; let k = 1; let n = 3; let l = 3; while (true){ if (4*q+r-t < n*t){ alert(n); yield n; ...

Removing Firefox's button outline when the mouse is pressed, not clicked, hovered over, or focused

Is there a way to remove the default outline that appears on my Bootstrap page button when it is pressed and not released? I have already tried targeting mouse focus and active states, but haven't been successful. Default Button https://i.sstatic.ne ...

What causes margins to collapse and how does display:inline-block prevent it?

Explore the concept of margin collapse in this example. .ct1{ background: red; margin:40px; border:1px solid;width:100%; } .ct2{ background: pink; margin:40px; border:1px solid;width:100%; } <div class="ctbox"> <div class="ct1">first</di ...

Is it possible to invoke a JavaScript function from within a CSS file?

Currently, I am focusing on developing responsive web design and looking for ways to avoid creating multiple versions of each page based on screen width variations. The struggle lies in managing font sizes effectively. While attempting to style them using ...

Support for other languages in Laravel with the Dompdf package

I utilized the dompdf package in my Laravel project to generate a PDF file. However, when attempting to display content in a language other than English (like Bangla) ??????????????????????????? characters appear. <body style="font-family: 'Ador ...

Importing styles from an external URL using Angular-cli

How can I load CSS styles from an external URL? For instance, my domain is domain.eu but my site is located at sub.domain.eu. I want to use styles that are stored on the main domain (common for all sites). The example below does not work: "styles&qu ...

Tips for performing addition with JSON data

How can I add up the values of qty in + (sum of qty) +? [{"qty": "34"},{"qty": "5"}] $.ajax({ url: "localhost/sp/text.json", //json link dataType: 'json', success: function(data) { var items = []; $.each(data, func ...

Encountering a 'redirect' error within the views.py file of a Django project

The registration form is working smoothly, however, I am encountering an issue with the redirect function in addUser. Upon attempting to save data in the admin panel, I am facing an error during the redirect process. from django.shortcuts import render,r ...

The height of scrollbars in the HTML section does not extend to full coverage

On my HTML webpage, I am facing an issue with the "left-section" scrollbar. It does not cover the entire height of the section. The scrollbar only appears when the window is resized small enough to reach "Link 18". Even then, the scrollbar does not scroll ...

Pass the code from the webpage to the PHP script

On my website, I have implemented a feature using JavaScript that dynamically changes the page content. Now, I am looking for a way to send this updated content to a PHP script. How can I achieve this functionality? ...