tobias47n9e
tobias47n9e

Reputation: 2231

CSS Grid: Border for incomplete rows

Is there a way to have a CSS grid (display: grid) that has a 1px border around all items and also fills incomplete rows? The approach of setting the background-color seems to not be a viable solution.

My goals would be to have a grid without the grey area in the code snippet where items are missing and the grid lines always extending all the way through the table. This should work for responsive combinations of items per row.

It almost seems like special pseudo classes would be needed for doesn't have item below and doesn't have item to the right to make this work in responsive layouts because last-of-type has too little information about the grid to use it for styling.

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  background-color: #d4d4d4;
  grid-gap: 1px;
  border: 1px solid #d4d4d4;
}

.grid > div {
  padding: 15px;
  text-align: center;
  background-color: white;
}
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

Upvotes: 6

Views: 1733

Answers (1)

Vadim Ovchinnikov
Vadim Ovchinnikov

Reputation: 14012

You should apply

  • the same background-color for grid container and grid items
  • right and bottom borders for grid items with negative margins (this will be compensated by grid gaps).

Demo:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  background-color: white;
  grid-gap: 1px;
  border: 1px solid #d4d4d4;
}

.grid > div {
  padding: 15px;
  text-align: center;
  background-color: inherit;
  border-right: inherit;
  margin-right: -1px;
  border-bottom: inherit;
  margin-bottom: -1px;
}
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

Upvotes: 4

Related Questions