Adjust the height of CSS Grid rows dynamically

I'm currently working on a CSS Grid layout, and I've encountered an issue with the "auto" value for row height sizing.

Despite having small content that should allow them to shrink, the items are maintaining a minimum height of 1fr.

For better clarity on the problem, here's a code example outlining the issue: you can also view it at https://codepen.io/16kbit/pen/RJbMWM

section {
  display: grid;
  grid-template-areas: "one top" "one bottom";
  align-items: start;
  border: 1px solid hotpink;
}

article {
  border: 1px solid green;
}

#one {
  grid-area: one;
}

#top {
  grid-area: top;
}

#bottom {
  grid-area: bottom;
  background: yellow;
}
<section>
  <article id=one>
    <h1>One</h1>
    <p>Lorem cool dolizzle sit amizzle, dope sizzle elizzle. Nullam shiznit velizzle, get down get down volutpizzle, suscipizzle quizzle, dizzle mammasay mammasa mamma oo sa, arcu. Pellentesque sheezy tortizzle. Sed erizzle. Fusce izzle dolor shiznit pimpin'
      tempizzle tempor. Maurizzle pellentesque nibh shizzlin dizzle turpizzle. Vestibulum in tortor. Pellentesque cool rhoncus black. In hac fo shizzle my nizzle check out this dictumst. Black uhuh ... yih!. Mammasay mammasa mamma oo sa tellizzle sh...
  </article>
  <article id=top>
    <h1>Top</h1>
    <p>Just Two Words</p>
  </article>
  <article id=bottom>
    <h1>Bottom</h1>
    <p>Help Me! How can I get closer to my Top neighbour?</p>
  </article>
</section>

The desired outcome:

I aim to have the #bottom item positioned as close as possible to the #top item, while allowing them to adjust their size based on their content.

Current outcome:

The CSS Grid is preventing the item's height from being smaller than 1fr unit (50% of total height) - influenced by the #one item with extensive text.

To illustrate visually, I am aiming for the layout shown on the right side rather than the current left-side result:

https://i.sstatic.net/R0BKn.jpg

Answer №1

After reviewing your question and response, it seems that you are missing a key aspect of grid layout principles.

In a grid layout, a row spans across the entire grid rather than being limited to a single column.

This means when you mention:

If we had three rows in our right column...

Such segregation does not exist as every row extends through all columns uniformly.

The diagram below depicts your layout using developer tools:

https://i.sstatic.net/HF99t.png

You can observe that each row covers all columns consistently.

The height of the third row is determined by the content in #one, as per your specifications.

The third row in the right column should match the height of the third row in the left column since each row can only have one height value.

However, you have the flexibility to adjust the size and alignment of grid areas within different rows and columns.

align-self: stretch (default setting)

https://i.sstatic.net/GzZC4.png

align-self: end

https://i.sstatic.net/swAvQ.png

align-self: center

https://i.sstatic.net/m1SGe.png

align-self: start (probably what you are seeking)

https://i.sstatic.net/7FrsI.png

section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto 1fr;
  grid-template-areas: 
            "one top"
            "one center"
            "one bottom";
  border: 1px solid hotpink;
}

article {
  border: 1px solid green;
}

#one    { grid-area: one;}
#top    { grid-area: top;}
#center { grid-area: center;}
#bottom { grid-area: bottom; align-self: start; background-color: aqua;}
<section>
  <article id=one><h1>One</h1><p>Lorem cool dolizzle sit amizzle, dope sizzle elizzle. Nullam shiznit velizzle, get down get down volutpizzle, suscipizzle quizzle, dizzle mammasay mammasa mamma oo sa, arcu. Pellentesque sheezy tortizzle. Sed erizzle. Fusce izzle dolor shiznit pimpin' tempizzle tempor. Maurizzle pellentesque nibh shizzlin dizzle turpizzle. Vestibulum in tortor. Pellentesque cool rhoncus black. In hac fo shizzle my nizzle check out this dictumst. Black uhuh ... yih!. Mammasay mammasa mamma oo sa tellizzle shiz, pretizzle shiznit, mattizzle fo, gangster vitae, nunc. Get down get down suscipizzle. Own yo' away izzle sed cool.Nullizzle fizzle shut the shizzle up yo mamma orci daahng dawg viverra. Phasellus nizzle shizzle my nizzle crocodizzle. Curabitizzle sure velit vizzle check out this dizzle doggy. Maecenas sapien nulla, iaculis shiz, molestie hizzle, egestas a, erizzle. Shit vitae turpis quizzle nibh bibendizzle boom shackalack. Nizzle pulvinar dope velizzle. Aliquizzle mammasay mammasa mamma oo sa volutpat. Nunc izzle its fo rizzle at lectus pretizzle faucibizzle. We gonna chung nec lacizzle own yo' fizzle pizzle ultricizzle. Ut nisl. Crunk et owned. Integer laoreet ipsum shizzlin dizzle mi. Donizzle at shiz.</p>
</article>
  
<article id=top><h1>Top</h1> <p>Just Two Words</p></article>
  
  <article id=center><h1>Center</h1></article>
  
<article id=bottom><h1>Bottom</h1><p>Help Me! How can I get closer to my Top neighbour?</p></article>
  
</section>

Answer №2

After experimenting further, I finally discovered a solution that works:

grid-template-rows: auto 1fr;

By setting the last item to 1fr, the other item is able to adjust its size using auto.

If we had three rows in our right column, the CSS would need to be:

grid-template-rows: auto auto 1fr;

This means that the first two items (auto) will resize based on their content, while the third item (1fr) will occupy any remaining vertical space.

In essence, at least one item must have a value of 1fr for the other items to be fully flexible with auto.

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

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

Javascript code for toggling the visibility of a div element not functioning as expected

This problem is becoming quite frustrating as it appears to be straightforward but still doesn't work. Inside my document, I have <div id ="splashscreen" style="display:block"> <h3>title</h3> <p>text</p> &l ...

Stylish Navigation Menu Logo/Site Name

Currently in the process of upgrading my website and I have my website name included as part of my menu, as opposed to a logo. This has been an easy solution that has worked well for me. For mobile screens, the template I purchased includes a slicknav men ...

managing the speed at which animated gifs are loaded and played

I am facing a challenge with a slideshow that features multiple animated gifs. Each slide is equipped with its own animated gif. My goal is to ensure that the animated gifs play in synchronization with the timeline I have set up in photoshop, starting fro ...

Issue with input-group background display in bootstrap 4

My new computer is running on Windows 11 with Chrome version 97. There seems to be a bug in the original bootstrap code, as evidenced by the attachment. The issue can be seen on the Bootstrap website By adding "border-radius:0!important" to ".input-group ...

Ways to place two anchor tags side by side within a list item contained within a justified navigation tab

I'm currently working with some nav-tabs and attempting to place two a tags within one of the li elements that represent a tab. However, I'm facing an issue where the a tags are appearing on separate lines. I've tried using inline styling fo ...

The issue of excess space surrounding images while utilizing Bootstrap 3

Hey there, I'm currently working on a website using Bootstrap 3 framework and I've run into a little snag. Whenever I add an image (just a regular one with an img tag), it seems to have some white space on both the left and right sides of the scr ...

Tips on choosing additional (sibling) elements with CSS?

My navbar has the following structure: <ul class="nav navbar-nav"> <li class="nav-item"><a href="#services">Services</a></li> <li class="nav-item"><a href="#work">Work</a></li> <li class ...

Transforming DataFrame into Desired HTML Table Structure in R

The dataframe provided below includes the following details: structure(list(Month = c("May-17", "A", "B", "C", "D", "E", "Apr-17", "A", "B", "C", "D", "E", "Mar-17", "A", "B", "C", "D", "E"), No = c(75L, 10L, 15L, 12L, 18L, 20L, 75L, 9L, 12L, 10L, 19L, ...

What is the method for rotating a map using JavaScript?

My map built with Leaflet displays a route and a moving car marker. Now, I am looking to implement a feature where the map rotates based on the direction of the car. I have access to both the current coordinates of the car and the target coordinates. ...

The background of the div fails to appear

Why is my div's background not displaying properly? Check out the code below: <div style=" width:676px; height:230px; display: inline; margin: 0 0 0 0; background-image: url('http://www.goodsstall.co.uk/ekmps/shops/goo ...

Styling HTML Select Box Options

My goal is to display the user's name and email within an option of a select box: <option>Adda <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caabaeaeab8aafb2aba7baa6">[email protected]</a></option& ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

Issue with CSS styles not linking correctly to ejs templates

I'm having trouble linking my CSS stylesheet in my project. I have the CSS file stored in a public folder with a css subfolder within it. Despite trying various methods, I can't seem to get the stylesheet to connect properly. Below is a snippet f ...

presentation not visible at first

I'm facing an issue with adding a slideshow to the header of my website. When the page initially loads, the slides do not appear; instead, I see the dots and arrows positioned higher than they should be. However, when I click on a dot or the "next pag ...

Tips on keeping display flex elements confined within a container

My goal is to add two divs to an element. The first div needs to have a fixed height and position. The second div should fill the remaining space, but not exceed it. I have created an example below to illustrate the desired result. #container { border ...

Utilizing PHP's $_POST function in conjunction with a table

Imagine a table arranged in a 4x4 grid, with all of the cells initially colored black. When you hover over a cell, it changes to grey. Now, I am looking for a way to make it so that when you click on a cell, it remains grey and its coordinates are passed ...

What strategies can I employ to prevent this bar from breaking?

How can I prevent my navigation bar from breaking when zoomed out? Below is the code snippet in question: <nav> <ul id="nav"> <li><a href="#">Home</a></li> <li><a href="#">What We Do</a></li> &l ...

Generating visual content from an application programming interface

<div class="row box"> <div class="col-md-4 pic"></div> <div id="temperature" class="col-md-4 change make_blue bigger_text"> Placeholder </div> <div class="col-md-4"> <button id="getChange" class="make_ ...

What is causing my HTML file path to function on my server, but not when I access the HTML file directly?

My file structure is organized as follows: The main file is located in the folder "HTML-Project/index.html". Within this folder, I have my style.css file and two other folders: one for pictures (HTML-Project/pictures) and another for categories (HTML-Proje ...