SteinTech
SteinTech

Reputation: 4068

how to fill remaining empty columns in css grid

I have a grid with 5 columns. In the picture, I've demonstrated that when columns 1, 2 and 5 are "filled", I want to place an item in the remaining columns 3 and 4.

I never know what columns are "occupied", so the code should be flexible (first empty to last empty).

enter image description here

Upvotes: 0

Views: 593

Answers (1)

Nidhin Joseph
Nidhin Joseph

Reputation: 10237

Using CSS use the :empty pseudo-class to check if an element is empty.

Using JS use innerHTML == '' to check if the element is empty.

document.querySelectorAll('.grid div').forEach(e => {
  if (e.innerHTML == '') {
    console.log(e);
  }
})
.grid {
  display: grid;
  grid-gap: 1em;
  grid-template-columns: repeat(5, 1fr);
}

.grid div {
  background: green;
}

.grid div:empty {
  background: Red;
}
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div></div>
  <div></div>
  <div>5</div>
</div>

Upvotes: 3

Related Questions