Design a CSS Grid that organizes content in columns, adjusting dynamically to fit the amount of content in each row

I am working with a dynamic set of elements, all the same size. My goal is to arrange these elements in a grid layout, organized in columns. The number of columns should adjust based on the width of the container, and the number of rows should adapt according to the total number of elements.

For instance, if there are 9 elements:

1 4 7
2 5 8
3 6 9

If the container width increases:

1 3 5 7 9
2 4 6 8

Or decreases:

1 6
2 7
3 8
4 9
5

This layout functions correctly when items are arranged by row, but not by column. Additionally, setting the number of rows explicitly works well, but using auto-fill for both rows and columns results in all elements being displayed in a single row.

Here is a straightforward example that I expect to render as a 3x3 grid: https://codepen.io/anon/pen/ZxPQNd

#grid {
  width: 320px;
  border: 1px solid red;
  display: grid;
  grid-gap: 10px;
  grid-auto-flow: column;
  grid-template-rows: repeat(auto-fill, 100px);
  grid-template-columns: repeat(auto-fill, 100px);
  grid-auto-columns: 100px;
  grid-auto-rows: 100px;
}

#grid>div {
  background: lime;
}
<div id="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
</div>

Answer №1

If you want a specific layout, you can utilize CSS multi-column layout by adjusting the column-width property. Here is an example:

#grid {
  border: 1px solid blue;
  column-width: 120px;
  column-gap: 12px;
}

#grid > div {
  break-inside: avoid-column; /* Ensure element stays within column */
  page-break-inside: avoid; /* Keep element from breaking in Firefox */
  background: cyan;
  width: 120px;
  height: 120px;
  margin-bottom: 12px;
}
<div id="grid">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
  <div>F</div>
  <div>G</div>
  <div>H</div>
  <div>I</div>
</div>

Answer №2

When arranging items in columns, everything works smoothly at first glance but not when organized by rows.

The reason for this is that block elements typically occupy the entire width of their parent element by default.

However, this behavior does not apply to height. In general, most elements have a height that matches their content (meaning no additional space).

Basically, your container has a style of width: 100% and height: auto. To achieve row-like behavior in the vertical direction, you need to add height: 100vh.

For more information, visit: How to make a div 100% height of the browser window?

#grid {
  width: 320px;
  border: 1px solid red;
  display: grid;
  grid-gap: 10px;
  grid-auto-flow: column;
  grid-template-rows: repeat(auto-fill, 100px);
  grid-template-columns: repeat(auto-fill, 100px);
  grid-auto-columns: 100px;
  grid-auto-rows:  100px;
  height: 100vh; /* NEW */
}

#grid > div {
  background: lime;
}
<div id="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
</div>


When it comes to rearranging grid items based on screen size, using grid-auto-flow: row will cause the items to adjust according to the container's width. On the other hand, with grid-auto-flow: column, the items will adapt to the container's height. If you want column-flowing items to respond to changes in width, some clever manipulation will be necessary.

Find more details here: Make grid items fill columns not rows

Answer №3

The original poster has posed the question perfectly. With an unknown number of elements to showcase and a viewport size that can vary, the challenge is to present these elements in a grid layout.

Adjusting the number of columns based on the viewport width is key here. One approach could involve using CSS media queries, but this method can be cumbersome and error-prone. The ideal solution should not rely on the viewport dimensions.

If all elements have a consistent fixed width, employing flexbox is a straightforward option. A sample code snippet might look like this:

#grid {
  display: flex;
  flex-wrap: wrap;
}

#grid div {
  flex: 1 0 110px;
  background-color: yellow;
  width: 100px;
  height: 100px;
  margin: 10px;
  max-width: 100px;
  text-align: center;
}
<div id="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
</div>

To allow elements to expand horizontally while still maintaining a uniform grid layout, utilizing CSS grid with repeat and minmax on grid-template-columns property is effective. Here's an example snippet showcasing this concept:

#grid{
display: grid;
grid-auto-flow: row;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
grid-template-rows: repeat(auto-fill, 1fr);
column-gap: 10px;
row-gap: 10px;
}

#grid div{
background-color: yellow;
height: 100px;
text-align: center;
}
<div id="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
</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

My jQuery function only activates when I manually adjust my window size to mobile, but doesn't work when I refresh the

I'm currently working on a code snippet to dynamically add and remove classes on mobile devices. It seems to function properly when I manually resize the browser window to mimic a mobile screen, but upon refreshing the page, it stops working. $(docum ...

Display React elements on the web page

Seeking assistance from anyone! I've been grappling with a problem and can't seem to figure out a solution. Here's the scenario: My current setup involves a sidebar and a top bar for navigation in React. Check out my app so far in this imag ...

Tips for avoiding the automatic focus on text fields that occurs when utilizing the placeholder attribute in HTML5

Imagine having a form with the placeholder attribute set as follows: <input type="text" name="something" placeholder="username" /> <input type="text" name="somethingelse" placeholder="password" /> Upon visiting the page with this form, the fi ...

Exporting data from AngularJS to Excel is not functioning correctly in Internet Explorer. Additionally, the exported Excel file does not display properly in Firefox and

I have been attempting to Export a table from a jsp page to Excel using AngularJs. Is Angularjs not compatible with IE? I am also encountering this error SCRIPT5009: 'Node' is undefined In Chrome and Firefox, the Excel file only opens when save ...

How can the hover effect be disabled when the pseudo-element is being hovered over?

I need the hover effect (the background of the pseudo-element changing to green) to only show up when the button is being hovered over. Right now, it also triggers when hovering over the pseudo-element itself (green box). button { box-sizing: border ...

Position the Figcaption over the Image

Running a website, I am facing an issue with adding copyright information to the top-left corner of an image. The img element is set to float:left; and the figcaption appears after it. However, there are some complications: 1) Using the position:absolute ...

Instructions on how to change the color of specific text to red

Issue: While working on my testimonials page, I am facing a problem with displaying an "ADMIN" tag in red color instead of normal stars for one of the responses by an admin. I have tried various solutions like removing the ending p tag and adding quotes to ...

Unable to concentrate on HTML input elements

TL;DR just click on this link I'm having a problem with my input elements - they seem to be on strike and not working properly. I've simplified the code to focus on the variables, and while I found some solutions that work, I believe there' ...

Customizing the appearance of a Form.Check (checkbox) component in React Bootstrap

I am new to React and Bootstrap. I have a question about styling Form.Check (checkbox) components. How can I customize the default appearance to achieve a different look, such as a switch or another style? Here is what I have attempted so far (I tried app ...

Easiest method to globally disable form autocompletion in an application without manually setting autocomplete off for every individual form

Is there a quick way to disable autocomplete in all forms within the application without individually adding "autocomplete=off" to each form? ...

Tips for defining conditions within the style attribute in JSP

Below is the code that I attempted: <div style="width:85%;"> <input class="formbutt" value="AddNew" title="AddNew" type="button" style="{(${projectEnvironmentBean.divStyle}=='dipslay:none') ? 'display:block' :'display: ...

Tips for creating an endless loop within a nested v-for in Vue?

Here is my attempt at solving the problem: HTML <ul class="tree"> <li> <span>First Node</span> <ul> <li v-for="(tree, i) in trees" :key="i"> <span v-text="tree. ...

In mobile browsers, the text within the <pre> tags appears extremely small. How can I adjust the font

My issue is with preformatted text that displays correctly on desktop browsers but appears very small on mobile devices in comparison to regular text. Adjusting the size using ems or percent causes it to be too large on desktop screens. Despite searching e ...

Addressing Browser Incompatibility in React.js Event Handling

I've recently embarked on my journey to learn React.js by delving into various tutorials and documentation. However, I'm encountering a peculiar issue specifically in Google Chrome: https://i.sstatic.net/qODiP.png Interestingly, in Firefox, it ...

How can you adjust the zoom level to 100% on an Android Webview?

Using Anddown to convert markdown to HTML and wanting to display it in a webview on a tablet screen, I encountered an issue. The webview, within a fragment, takes up half the screen in landscape mode. The challenge was getting the HTML content to appear a ...

HTML Autocomplete Error 404 Resolved with ASP.NET and JQuery

My autocomplete feature in an ASP.NET project is not working, despite trying different methods. I have set up a database called Diagnose, but when I try to implement it, I keep getting a 404 error on jQuery. Below is my HTML code: <script src="htt ...

Angular: "btn" class vanishes when the button is toggled

I am facing an issue with the button's class change functionality. I am using the [ngClass] directive to switch between Bootstrap classes for the button style. However, when I click the button, the "btn" class seems to disappear from the code. Instead ...

Using a regular expression to swap out the final image tag or character

Recently, I encountered an HTML string that resembles the following: <html> <head> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> </head> <body style="font-f ...

Issue with AngularJS in Internet Explorer 7: "querySelector" property or method not supported by object

Incorporating angularjs into an existing asp.net project has presented a challenge due to the project's dependency on IE 7 compatibility mode. Upon running the project, an error from the angularjs file was encountered: Object doesn't support pro ...

Using jQuery to update a table, however, the browser is failing to automatically refresh the

I have developed a node.js and sockets app to create a Single Page Application (SPA). The user can fill out a form to create a new lobby. Upon submission, a socket event is sent to the server, where the new lobby is added. The server then emits an event to ...