0

I've got a simple grid with auto-fit columns. So depending on the available screen width one, two, three or more items get displayed in a row.

The challange: The last item of each row should always be styled different. Can this be achieved out-of-the-box with css grid or do I need media queries for that?

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
<div class="grid">
   <div>Item 1</div>
   <div>Item 2</div>
   <div>Item 3</div>
   <div>Item 4</div>
   <div>Item 5</div>
   <div>Item 6</div>
</div>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
nerdess
  • 10,051
  • 10
  • 45
  • 55
  • You'd need MQ or JS for that. CSS doesn't "know" which element is last on a row, – Paulie_D Nov 04 '21 at 11:22
  • What sort of styling do you need. Sometimes background color for example can be achieved through positioning, but more complex stuff would need calculation. – A Haworth Nov 04 '21 at 11:25
  • @AHaworth I am placing a vertical divider between each item using :after but on the last item of each row there should not be one – nerdess Nov 04 '21 at 11:27
  • better update your question with that requirement because we can do the divider thing without the need to know the last item – Temani Afif Nov 04 '21 at 11:27
  • here is how: https://stackoverflow.com/q/56012789/8620333 – Temani Afif Nov 04 '21 at 11:29
  • @TemaniAfif The solution uses overflow:hidden which is in my opinion not very elegant as it can cause trouble down the line. My question is more of a general nature since I've implemented the desired design using media queries already. I wanted to simplify it though. – nerdess Nov 04 '21 at 11:39
  • 1
    then the answer to your generic question is a No. You still need to wait to have such selector: https://stackoverflow.com/a/68756301/8620333 – Temani Afif Nov 04 '21 at 11:42
  • For the specific 'hide last vertical bar' you could probably overlay it with a white (for example) pseudo element on the parent - but not sure it's worth it. – A Haworth Nov 04 '21 at 16:54

0 Answers0