Search code examples
cssresponsive-designcss-grid

Select all the elements of the last row of a grid with a responsive design


I've created a grid of elements using grid, and every elements from a row is separated with a bottom border. I would like to remove this border bottom line for all the elements from the last row. This grid displays 6 elements at first but once I click on a view more button it displays 15 elements

I've used media query to find the breakpoints and used nth-last-child to make it responsive like this:

.grid-item:last-child {
  border-bottom: none;
}

@media (min-width: 540px) {
  .grid-item:nth-last-child(-n + 2) {
    border-bottom: none;
  }
}

@media (min-width: 920px) {
  .grid-item:nth-last-child(-n + 3) {
    border-bottom: none;
  }
}

And it works the way I want except when I click on the view more button and then, between 540px and 920px, the number of elements of the last row is not 2 but only one, and so it selects an elements of the last row as well because it takes the two last elements. I wants to prevent this behavior and only select the elements of the last row


Solution

  • A simple, if somewhat hacky, way might be to put a top border on each item and cover-up the ones from the top row with a pseudo element.

    .grid {
      display: grid: grid-template-columns: repeat(5, 1fr);
      position: relative;
    }
    
    .grid::after {
      content: '';
      top: 0;
      left: 0;
      width: 100%;
      height: 2px;/* note slightly taller than the borders to compensate for 'rounding errors' */
      position: absolute;
      background-color: white;
    }
    
    .grid>* {
      position: relative;
      height: 50px;
      background: cyan;
      border-top: 1px black solid;
    }
    <div class="grid">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>