Search code examples
htmlcsstailwind-csscss-grid

How do I set an indeterminate height on a column that spans multiple rows with CSS Grid?


I'm using Tailwind CSS and attempting to use a grid layout which looks like below:

my content layout

I have some dashboard-type metrics in Div 1. Now, when I add a very long ordered list to Div 2, for some reason, it's stretching Div 1's height to (what appears to me) to be the overall height of Div 2.

Hopefully this screenshot makes clear what is happening. You can see the height of that top Div (Div 1) is enormous after adding the content to the right Div column:

what happens when adding content to Div 2

The code I've used is basically copy/pasted directly from a Tailwind Grid generator as shown below:

<div class="grid grid-cols-3 grid-rows-4 gap-4">
    <div class="col-span-3">1</div>
    <div class="row-span-3 col-start-3 row-start-2">2</div>
    <div class="col-start-1 row-start-2">3</div>
    <div class="col-start-2 row-start-2">4</div>
    <div class="col-span-2">5</div>
    <div class="col-span-2 row-start-4">6</div>
</div>

I've simply placed my own content in their respective Div's, but it's behaving unexpectedly.

My goal is to basically have all Div's in the Grid have a height that is as big as the content in its respective Div.

EDIT: Similar to how this pen works. Although the pen uses custom css stylings. Ideally, I'd like to use the Tailwind CSS classes to achieve the same result.

https://codepen.io/source-matters/pen/YzJaBRL?editors=1100


Solution

  • The behavior you are seeing is because you have applied grid-template-columns: repeat(4, 1fr) via grid-rows-4. This instructs the layout that each track should be ¼ of the height. So if the last three row tracks are tall because of content, this will elongate the first row track so that it adheres to the ¼-height stipulation. Instead, you could consider telling the layout that the first row track should not be a fraction of the overall height at all:

    <script src="https://cdn.tailwindcss.com"></script>
    
    <div class="grid grid-cols-3 grid-rows-[auto_repeat(3,1fr)] gap-4">
        <div class="col-span-3 bg-red-200">1</div>
        <div class="row-span-3 col-start-3 row-start-2 bg-green-200">
          <div class="h-96">Foo</div>
        </div>
        <div class="col-start-1 row-start-2 bg-yellow-200">3</div>
        <div class="col-start-2 row-start-2 bg-violet-200">4</div>
        <div class="col-span-2 bg-blue-200">5</div>
        <div class="col-span-2 row-start-4 bg-sky-200">6</div>
    </div>