Utilizing CSS Grid to create a layout with the fewest columns while allowing for automatic flow once elements wrap

Is it possible to create a CSS grid layout with automatic flow that adjusts the number of columns after wrapping? How can this be achieved?

Currently, I have a grid containing 6 items with auto-placement. When all 6 items do not fit in a single row, I would like the grid to display them in 3 columns and 2 rows instead of 5 columns and 1 row where the second row only has one element.

I am looking for a solution that does not involve the use of media queries.


A visual example of what I want to achieve:

1) If all 6 items fit in one row, they should be displayed in a single row as follows:

| OOO OOO OOO OOO OOO OOO | 
| O1O O2O O3O O4O O5O O6O |
| OOO OOO OOO OOO OOO OOO |

2) If fewer than 6 elements fit in one row, they should be represented in 2 rows with 3 items each:

| OOO OOO OOO         | 
| O1O O2O O3O         | 
| OOO OOO OOO         | 
|                     | 
| OOO OOO OOO         | 
| O4O O5O O6O         | 
| OOO OOO OOO         | 

3) If fewer than 3 elements fit in one row, they should be arranged in 3 rows with 2 items each:

| OOO OOO   | 
| O1O O2O   | 
| OOO OOO   | 
|           | 
| OOO OOO   | 
| O3O O4O   | 
| OOO OOO   | 
|           | 
| OOO OOO   | 
| O5O O6O   | 
| OOO OOO   | 

Here is the progress I've made so far: I adjust the width until the last column wraps, at which point I'd like to switch to a layout with 3 columns, each containing three items, rather than continuing with 5 columns and then having one item on its own.

.grid {
  padding: 10px;
  border: 2px solid #444;

  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 10px;
  justify-content: space-evenly;
}

.item {
  height: 50px;
  background: #5a5a;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2em;
}
<div class="grid">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
</div>

Answer №1

Note: This answer was written prior to the inclusion of the OP's code in the question. Nevertheless, I believe that utilizing @media queries remains essential in addressing the issue at hand, regardless of how the div elements are presented.


Initial Response:

I've created a sample below incorporating a br tag and utilizing @media queries.

Execute the snippet and click 'Full Page' to evaluate it:

.grid-box {
  display: inline-block;
  width: 200px;
  height: 150px;
  background-color: blue;
  margin: 2px;
}

.row3 {
  display: none;
}

@media (max-width: 1260px) {
  .row3 {
    display: block;
  }
}

@media (max-width: 636px) {
  .row3 {
    display: none;
  }
}
<div class="grid-box"></div>
<div class="grid-box"></div>
<div class="grid-box"></div>
<br class="row3">
<div class="grid-box"></div>
<div class="grid-box"></div>
<div class="grid-box"></div>

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 preventing the adjacent DIVs from aligning on the same row as this DIV?

In the code snippet below, I've introduced another div.website-thumbnail. However, the div containing <span class="website-title">Business Coach</span> appears isolated on its own line, almost as if it has clear: left; applied to it. None ...

The functionality of nth-child(odd) seems to be malfunctioning when there is a change

When I group certain elements together in one container, I like to make odd elements stand out by giving them a different background color. However, when I try to filter elements based on conditions and move unwanted elements to another class, the nth-chil ...

Is there a way to adjust the image dimensions when clicked and then revert it to its original size using JavaScript?

Is there a way to make an image in an HTML file change size by 50% and then toggle back to its normal size on a second click using JavaScript? I've attempted to do it similar to the onmouseover function, but it doesn't seem to be working. Any sug ...

Unable to adjust the width of a table column within a horizontally scrollable container

I am struggling to resize the columns of a large table with 20 headers. Despite trying to place the table inside a div with overflow:auto, I still cannot achieve horizontal scrolling or make the div expand when resizing the columns. A sample code snippet ...

challenges surrounding the use of getElementByTagName

Within my webpage, I have implemented two select elements, both containing multiple options. However, I am facing an issue where I can only access the options from the first select box using getElementByTagName("options"), and unable to retrieve the option ...

div positioned on top of additional div elements

My HTML code consists of simple div tags <div class="left">Project Name: </div> <div class="right">should have a name</div> <div>Shouldn't this be on a new line?</div> These classes are defined in a stylesheet as ...

What are the steps to effectively utilize <ul> for showcasing scrolling content?

I stumbled upon and found it to be a great inspiration for my project. I tried replicating the layout of the listed items on the site: .wrap { display: block; list-style: none; position: relative; padding: 0; margin: 0; border: ...

Clicking on a Vuetify v-btn with the :href attribute set to download will open the XML file

I'm having trouble getting the v-btn to download an XML file instead of opening it in the browser. <v-btn :disabled="!exportUrl" block x-large height="100" color="primary" :href="exportUrl" download> ...

Struggling to use the innerHTML method to update a div within another div element?

<!DOCTYPE html> <html> <head> <title>Business Information Card</title> <script type="text/javascript"> window.onload = init; function init(){ var button = document.getElementById("populate ...

Creating margin on a canvas with jsPDF is a simple task that can be accomplished

Hi there, I'm currently working on generating a PDF from HTML using jsPDF, but I've run into an issue with setting page margins. I would really appreciate any assistance on how to add margins to my pages using the canvas object. Below is the sou ...

Looking to validate each input field individually using jQuery?

I am in need of validating all form inputs in the keyup function without having to write validation for each individual input. Is there a way to achieve this using methods like each();? Apologies for what may seem like a silly question. ' ...

Retrieve the selected option value from a dropdown menu when hovering or making a change within the same event

Apologies for my poor English. Is there a way to retrieve the value of a select box when a user either changes the select box or hovers over it with just one event? I attempted the following code snippet but it did not work as expected: jQuery("select[nam ...

Tips for presenting information on HTML webpages with the help of JavaScript

I am facing an issue with displaying data in HTML using JavaScript. The problem is that my code only shows the most recent data instead of all the data. My development platform is phonegap. Below is the snippet of code that I am having trouble with: var ...

In the email header, the first column will be announced twice in voice over for ADA compliance on iOS

I am currently working on designing an email template that is ADA (Accessibility) compliant. One issue I have encountered is that the first header in the table is being announced twice when read through voice over. For example, if "Item" is the first col ...

Display or conceal various objects using a single button in HTML

I've been working on creating a chatbot widget for my website, but I've run into an issue. The "Chat with us" button only shows the bot and not the close button as well. Here's what I've attempted: <input id="chat" type="button" on ...

What is the solution for resolving a significant spacing issue within a block of text?

I noticed that there is a significant gap between two of my divs when viewed in a browser. Here is the code: <div id="title-1"> <p>XYZ Corp is excited to introduce our latest project - Discover XYZ</p> </div> <d ...

What is the method to set up the "materializecss" modal with the "before" (beforeload) feature?

Trying to implement the modal functionality in my project using the materializecss framework but facing some challenges. I have created a popup modal for an image with the code below: HTML: <div class="media-insert"> <a href="#img2" class="moda ...

What is the best way to horizontally center items within an unordered list (ul li) inside a div class

I'm attempting to center a horizontal lineup of small icons. In the Launchrock platform, users have the ability to customize all code. Unfortunately, I do not have access to their default CSS, but we are able to override it. <div class="LR-site-co ...

Loading content with AJAX without having to refresh the page

I've been working on implementing a way to load content onto a page without needing to refresh it. While I was able to achieve this, I encountered a problem where the images and CSS files weren't loading properly. Below is the code I used: < ...

Add HTML code to the dataTable

I am working on an ajax function that receives HTML response containing table data like this: <tr><td>data1</td>td>data2</td>td>data3</td></tr> My question is, can I add this response to a dataTable row in the fo ...