CSS Grid with dynamically changing number of rows set to "auto", while ensuring one row always has a fixed size of "1fr"

Currently, I am experimenting with a CSS grid-based frontend and have encountered a specific requirement that keeps repeating itself in various parts of the frontend:

  1. A grid with a dynamic number of rows.
  2. Each row should be of variable size (auto).
  3. The final row must fill up all remaining space.

For instance, to achieve this for five rows, I use the following code snippet:

.myGridForFiveRows
{
    display: grid;
    grid-template-rows: auto auto auto auto 1fr;
}

Nevertheless, I am looking for a stylesheet that can provide the desired behavior regardless of the number of rows. Perhaps utilizing repeat() might help me achieve this?

https://developer.mozilla.org/en-US/docs/Web/CSS/repeat

.myGrid
{
    display: grid;
    grid-template-rows: repeat(auto-fit, auto) 1fr;
}

I have experimented with variations of repeat(auto-fit, auto) and repeat(auto-fill, auto), which unfortunately are not valid CSS, unlike repeat(4, auto) or repeat(auto-fill, 30px).

Any suggestions? While it is not an insurmountable issue, ensuring that "display n properly sized rows, then let the last element take up all the remaining space" aligns with the default behavior for all elements in my specification...

Answer №1

After considering your specific requirements:

  1. You need a grid that can have a varying number of rows.
  2. Each row should adjust its size automatically.
  3. The last row must consume all remaining space available.

For achieving this layout, Flexbox is an excellent choice and might be the perfect solution based on additional requirements. An example code snippet is provided below.

If you are set on using Grid Layout, it may not fulfill your needs completely. As per the current Level 1 specification, it cannot handle such demands.

The closest implementation in Grid would look like this:

grid-template-rows: repeat(auto-fit, minmax(auto, 1px)) 1fr;

Unfortunately, this syntax is unsupported by the current grid specifications.

repeat(auto-fit, auto) 1fr

You attempted to use this code, but it's invalid because auto and fr cannot be combined with auto-fit.

7.2.2.1. Syntax of repeat()

When using automatic repetitions (auto-fill or auto-fit), intrinsic or flexible sizes cannot be mixed.

  • Examples of intrinsic sizing functions include min-content, max-content, auto, fit-content().

  • Flexible sizing functions encompass <flex> values (e.g., fr).

To address the limitation with auto, you could try something like this:

repeat(auto-fit, minmax(auto, 1px)) 1fr

minmax(min,max)

This function defines a size range between min and max, inclusive.

If max < min, then max is neglected and minmax(min,max) is treated as min.

A <flex> value can only act as the track’s flex factor and cannot be used as a minimum.

This method correctly sizes your rows based on content, regardless of whether the container has a default height setting or specified height / min-height. View the demo for clarification.

However, the issue with the last row remains unresolved due to the invalid

1fr</code], causing the entire rule to fail. A working solution would utilize:</p>

<h2><code>repeat(auto-fit, minmax(auto, 1px)) 10em

In this scenario, the auto-fit does not behave as expected—the 10em applies to the second row instead. Refer to the demo for details.

This setup also encounters issues when the container specifies a height or min-height. Review the demo for more insights.


Despite the widespread availability of CSS Grid Layout, Flexbox still serves as the superior option in certain scenarios.

It meets all your criteria with straightforward and concise code:

article {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

section:last-child {
  flex-grow: 1;
}

section {
  /* flex-basis: auto <-- this is a default setting */
  margin-bottom: 10px;
  background-color: lightgreen;
}

body {
  margin: 0;
}
<article>
  <section>text text text</section>
  <section>text text text text text text text text text text text text ...
    </section>
  <section>text text text ...</section>
  <section>text text text ...</section>
  <section>text text text ...</section>
</article>

Answer №2

One workaround is to input an extremely large number for the repeat value that you know will never be reached. For instance, you could try this approach for the grid-template-rows:

grid-template-rows: repeat(100000000, auto) 1fr;

I encountered a similar problem and found success with this method.

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

I'm curious as to why the web browser is showing a timestamp below the image I have on my HTML page

Issue at Hand: I am currently working on coding a website that involves displaying an image. However, when the image is loaded, a timestamp appears underneath it in the web browser. Query: Could you please shed some light on why a timestamp is showing up ...

Creating two columns using React and Material-UI Grid while utilizing just one map function for iteration

I am facing a challenge with Material-UI Grid. I want to display the information from my map function in two columns instead of one. I tried adding another Grid item sm={6} and using the same map function, which resulted in two columns but with identical i ...

Tips for retrieving specific database entries using a JavaScript function

I'm currently in the process of developing a web directory that showcases organizations based on the selected county by utilizing an XML database. During testing, I have configured it to only display organization names and counties for now. However, ...

What makes the nav class different from the navbar class in Bootstrap?

Recently, I delved into learning about bootstrap and web development. To my surprise, I stumbled upon the nav and navbar classes in bootstrap 4. I'm curious to know what sets them apart from each other and when it's best to use one over the other ...

Certain HTML code on a webpage is currently inaccessible to me

Struggling with web scraping on a webpage due to inaccessible code. The part of the page's code that remains out of reach is only accessible through an anchor tag, with the following html: <a class="MTLink" href="#d192633539-47" title="example" &g ...

My image is being cropped on larger screens due to the background-size: cover property

I am currently in the process of designing a website with a layout consisting of a Header, Content, and Footer all set at 100% width. To achieve a background image that fills the screen in the content section, I utilized CSS3 with background-size:cover pr ...

What is the best way to create a new row at a specific index in an ng-repeat loop?

My Goal: I am aiming to insert a new row of ul after every 2 elements in my ng-repeat loop. For example: <ul class="col-sm-2"> <li><p>Automobile & Motorcycle</p></li> ...

Turn off hover opacity effect for a specific image

Currently, I've implemented a hover opacity effect on my images using the following CSS: img { opacity: 1.0; filter: alpha(opacity=1.0); } img:hover { opacity: 0.6; filter: alpha(opacity=0.6); } However, I now have a specific image for whi ...

Is it possible to modify this code to accept multiple IDs at once?

I'm attempting to create a form in JavaScript where, upon entering the necessary details and clicking submit, the user's email client opens with the information pre-filled for easy sending. However, I am facing challenges as my code involves mult ...

Incorporate negative padding in order to smoothly scroll to a specific ID

When I jump to an ID using domain.com/#section, the scroll goes too far down and needs a negative margin added. Is there a way to achieve this directly in the URL without relying on CSS, jQuery, or JavaScript? ...

The inputs are not responding to the margin-left: auto and margin-right: auto properties as expected

I'm having trouble aligning an input in a form to the center. Even though I have included display: block in the CSS, using margin-left:auto and margin-right: auto is not yielding the desired result. To illustrate the issue more clearly, I've cre ...

Attempted everything... Clicking away but a div refuses to show up post-click, resulting in an error message

When attempting to click a button, I encountered an error stating that the element is not clickable at point (1333, 75) as another element would receive the click. This issue arose while using Google Chrome version 65. <li class="slds-dropdown-trigge ...

Guide to displaying an input box depending on the selection made in a Mat-Select component

I am working on a mat-select component that offers two options: Individual Customers and Organizational Customers. When selecting Individual Customers, the dropdown should display three options: First Name, Last Name, and Customer Id. However, when choosin ...

Ways to Fix the React Hydration Issue in Next.js

I have been encountering an issue with the error message "Hydration failed because the initial UI does not match what was rendered on the server." I am unsure of what is causing this error and would appreciate any insights or suggestions from others who ma ...

The skipping of crucial text in tab focus is adversely affecting the accessibility of the website

My appbar contains an image link, a warning indicating the user's current environment, and details about the logged-in user. While testing accessibility with a screen reader, I noticed that tab focus skips over the user details in favor of a link in ...

What are some methods for submitting an HTML form to a CSV file?

I've been racking my brain for the past few days trying to find a viable solution to this problem. My project requires 100 individuals to take turns sitting at a computer and filling out a form I created. Each time someone submits their information, ...

I keep encountering an Uncaught TypeError when trying to read the property 'options' of null, despite having the element ID properly defined

I am a newcomer to the world of Javascript and HTML. Despite having the element defined in HTML, I am encountering an exception. Could someone please offer assistance? My goal is to create a shape (initially a circle) based on user input such as shape type ...

Ways to avoid losing data when a page is refreshed

After encountering a frustrating issue with my form, I turned to research in hopes of finding a solution. However, each attempt has resulted in disappointment as the data is lost every time the page is refreshed. If anyone has advice on how to prevent th ...

Maximizing the Potential of Bootstrap 5's Grid System

I'm struggling a bit with the Bootstrap grid system. I want to create 6 divs or containers that span the full width on smaller devices like mobiles, use 25% of the width on medium devices like tablets, and display all 6 in a single row on large deskto ...

Adjusting the size of the div both horizontally and vertically in Angular 5 using the mouse cursor

As a beginner in Angular 5, I am looking to achieve horizontal and vertical resizing of a div by dragging with the mouse pointer. Can someone assist me in implementing this feature? ...