4

I have a CSS grid with 3 rows. There may be less than 3 items to fill it, and I want to start filling it from the bottom.

I've created a jsFiddle for you to play with, but it currently fails to do what I want.

html, body, div {
  height: 100%;
}

div {
  display: grid;
  grid-template-columns: 1;
  grid-template-rows: repeat(3, 1fr);
  /* MISSING RULE */
}
<div>
  <p>Last item</p>
  <p>Second last item</p>
  <p>Top item</p>
</div>

Actual output:

Last item
Second last item
Top item

Desired output:

Top item
Second last item
Last item

I'd like to apply one rule to the <div> that contains the grid, rather than separate rules to the items in the grid, if that is possible.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
James Newton
  • 6,623
  • 8
  • 49
  • 113

2 Answers2

-1

There is no column-reverse function in CSS Grid, like there is in flexbox.

Therefore, getting grid areas to populate a container starting from the bottom isn't possible with a single rule in the container.

Here's how it would work in flexbox:

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

p {
  flex: 1;
}


/* demo styles */
p {
  margin: 0;
  background-color: lightgreen;
}
p + p {
  margin-bottom: 10px;
}
body {
  margin: 0;
}
<div>
  <p>Last item</p>
  <p>Second last item</p>
  <p>Top item</p>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
-3

If you want to use CSS Grid layout it will be like this. I modify your HTML. You have to write CSS property for grid child item where to start and where to end. grid-row-start: and grid-row-end:. Here is a CodePen.

  .grid-item{
      border: 2px solid red;
      border-radius: 5px;
      height: 200px;
      padding: 10px;
      width: 300px;
      margin-left: auto;
      margin-right: auto;
      display: grid;
      grid-template-columns: 1fr;
      grid-template-rows: repeat(3, 1fr);
    }
    .grid-item p{
      margin: 0;
    }
    .grid-item .first-item{
      grid-row-start: 1;
    }
    .grid-item .last-item{
      grid-row-start: 3;
    }
<div class="grid-item">
        <p class="last-item">Last item</p>
        <p class="second-item">Second last item</p>
        <p class="first-item">Top item</p>
    </div>
    

If you want to use flexbox it will be using two line code.

<div>
    <p>Last item</p>
    <p>Second last item</p>
    <p>Top item</p>
</div>

CSS for this

div{
    display: flex;
    flex-direction: column-reverse;
}

The flex-direction CSS property sets how flex items are placed in the flex container defining the main axis and the direction (normal or reversed).

TylerH
  • 20,799
  • 66
  • 75
  • 101
Rahul
  • 2,011
  • 3
  • 18
  • 31
  • OP says the number of items is dynamic so you won't know how to apply the `n-item` classes. – TylerH Apr 03 '20 at 13:56