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

The jQuery selectors are not able to identify any dynamically generated HTML input elements

After successfully injecting HTML code into the DOM using Ajax, I encountered an issue where my jQuery selector was not working for a specific HTML input element. For example, when attempting to use the following jQuery code: $("input[id*='cb_Compare ...

Does Vue3 support importing an HTML file containing components into a single file component (SFC)?

I am working on a Form-Component (SFC) that is supposed to import an HTML file containing Vue components. Form-Component <template src="../../../views/form-settings.html"></template> <script setup> import Button from "./. ...

A step-by-step guide on implementing the bootstrap paginator library to paginate PHP echoed data

I'm currently working on a project that involves displaying data from a database in a table. To make the data paginated on the client side, I decided to use the bootstrap paginator library available at: Below is the code I'm using: In my header ...

Bootstrap doesn't display in the dropdown menu

Struggling to get a dropdown menu to display on my page, my HTML code is: <div class="dropdown d-inline"> <div class="widget-header mr-3"> <button href="#" class="icon icon-sm rounded-circle border" data-toggle="dropdown"><i cl ...

What is the best way to center align the div container horizontally?

Trying to center the #container but all methods have failed. How can I achieve centering using only CSS? body { text-align:center; } <div id="app"> <div id="container"><div id="container_red" style="position:absolute;left:0"> ...

Engaging with the CSS content attribute

Below is a code snippet that inserts an image before the header tag. Is there a way to incorporate JavaScript or jQuery in order to execute certain actions when the inserted image is clicked? h1::before { content: url(smiley.gif); } The HTML code fo ...

Tips for referencing the second class when two classes share the same name in Selenium WebDriver

I am trying to retrieve the text from the second "109-top-dark-grey-block ng-binding" class, which is currently null but will contain some text in the future. I have attempted using tabIndex and nth-child selectors, but neither have been successful. " < ...

What is the best way to utilize a color picker to apply CSS color to a parent element?

When the pencil glyphicon is clicked, a color picker appears. I only want to apply the selected color from the color picker to the list elements that are the grand parent of the pencil glyphicon. Here's a snippet of my Ruby front-end code: <% cat ...

When the if-else statement is executed, it showcases two strings:

Learning Experience: Unveiling My Lack of Cleverness Update: It appears that utilizing PHP in my current setup is not possible. As a result, I'll take some time to contemplate while banging my head against a wall. Despite that, thank you all for your ...

A guide on retrieving values from programmatically created input elements in Java

Here's the HTML code that I am currently working with: <form method="get" action="#" id="startForm"> <input type="text" name="period" id="period" placeholder="The number of days"/> <input type="submit" name="submit" value="subm ...

The <HTML> element is just a bit too big for the screen

When viewing my webpage on mobile, the video background does not fit the screen properly (it fits in landscape orientation). Here is the video tag I am using: <video autoPlay loop muted playsInline className='absolute w-full h- ...

Is there a way to integrate the javascript and jQuery functions in order to conceal a button?

I recently acquired the File Upload script known as Simple Photo Manager and I am looking to incorporate jQuery functions with the existing JS code in the script. My main goal is to make the Delete button disappear once it has been clicked. However, I am ...

Safari is currently experiencing compatibility issues with iPad, resulting in a malfunction

I encountered a unique issue with my most recent website project. The website is built on WordPress, and the custom theme I created is presenting an unexpected problem: Despite functioning perfectly on all browsers and devices, the site fails to display p ...

Adjust the size of the image as needed in order to fit within a container of fixed

Is there a clever way to use CSS and/or JavaScript/jQuery to adjust the size of images only when necessary for them to fit within a fixed-height container alongside the remaining content? Upon reviewing the images in the 'new this week' and &apos ...

In both Chrome and Edge, the default value for the <select> tag is successfully set, however, this functionality is not working in

I have defined two values in the created method, 2018 and My Name, and assigned them to separate data properties. These data properties are then passed as v-bind to a component. The issue I am facing is that in Chrome and Edge, both values are set as defa ...

Resolving Issues with Page Feature Images on Your WordPress Site

Currently enrolled in a web development course, I collaborated with my instructor to create a custom website. However, I am facing an issue where the header image appears shorter on the Resources page () and Contact page () compared to the Blog page (). De ...

Adjusting Google Maps API v3 Autocomplete dropdown width with JavaScript and SASS to match input field dimensions

I am facing an issue where the autocomplete dropdown (div with class "pac-container") is consistently 4 pixels shy of aligning perfectly with the right side of the input field. It looks like this: Below is the HTML code: <input id="autocomplete" size= ...

Is there a foolproof method to verify if a user truly has visibility of a div element?

When I search online, most solutions only consider the viewport and/or the first parent container that is scrollable when trying to determine if a div is visible. However, I am wondering if there is a foolproof method to check if a div is truly visible t ...

The background image in the hovering textbox shifts and changes size

I've been trying to set a background image on a Kendo UI Textbox. It looks good until you hover over it. But when you do hover over it, this issue arises: How can I resolve this? The background image should remain in place even when I hover and cli ...

Skip the loading screen and directly retrieve meshes from the GWT server

I have a unique challenge with my animated models, each ranging from 5Mb to 8Mb in size. Downloading them individually can be time-consuming, especially when I need them on demand rather than preloading them in libGdx. While I am experienced with both GWT ...