Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to explicitly make a grid item appear always on the last row or last column?

Tags:

html

css

css-grid

I want to place a grid item to be always on the last row and / or on the last column of a grid. Even if I don't know how many rows or columns the grid might have. Is something like that possible?

This would be my grid:

.columns {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min-content, 16.5rem));
  grid-gap: 1rem;
}

I only found placement by explicit rows or columns: MDN

like image 401
Benedikt Avatar asked Oct 20 '25 09:10

Benedikt


2 Answers

Following my comment; from https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid#Counting_backwards

We can also count backwards from the block and inline end of the grid, for English that would be the right hand column line and final row line. These lines can be addressed as -1, and you can count back from there – so the penultimate line is -2.

like image 81
MatTheCat Avatar answered Oct 21 '25 23:10

MatTheCat


You can use a pseudo element :after to place an element at the end of the grid - see demo below:

.columns {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min-content, 16.5rem));
  grid-gap: 1rem;
}

.columns div {
  border: 1px solid;
  height: 100px;
}

.columns:after {
  content:'';
  display: block;
  border: 1px solid red;
  height: 100px;
}
<div class="columns">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Or you can use order property to place the element to the end - if any other grid item has order property, just give a large value. See demo below:

.columns {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min-content, 16.5rem));
  grid-gap: 1rem;
}

.columns div {
  border: 1px solid;
  height: 100px;
}

.columns .last {
  order: 1;
  border: 1px solid red;
}
<div class="columns">
  <div></div>
  <div></div>
  <div></div>
  <div class="last"></div>
  <div></div>
  <div></div>
  <div></div>
</div>
like image 41
kukkuz Avatar answered Oct 21 '25 22:10

kukkuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!