This is why you should learn CSS Grid

This is why you should learn CSS Grid
0

#1

Heres a simple codepen I’m proud of. Maybe when I have more time I’ll add animations!


#2

I like the your style.

How about this to replace the nested for loops?

$ghosts.innerHTML = ghostNames.reduce((html, ghost) => html + `
  <div class="ghost" id="${ghost}">
    ${pixels.reduce((pixHtml, pixel) => pixHtml + `
      <div class="square ${colorMap[pixel]}"></div>`,"")
    }
  </div>
`,"");

or this slightly more readable version using map?

$ghosts.innerHTML= ghostNames.map(ghost => `
  <div class="ghost" id="${ghost}">
    ${pixels.map(pixel => `
      <div class="square ${colorMap[pixel]}"></div>
    `).join('')}
  </div>
`).join('');

#3

Thanks @RandellDawson! I could use map or reduce, but I’m thinking that performance would be the same since the higher order functions are also nested. Is there something that I’m missing?


#4

Performance-wise, all of those createElement calls in your nested for loops creates an overall slower result than a single update to one element’s ($ghost) innerHTML property. Based on that, the performance may be equal. If you used nested for loops with the single innerHTML update, there might be a slight performance gain, but probably not because there are only there are not a significant number of elements in the pixels array.


#5

Ahh, that makes a lot of sense. I’ve always felt hesitant to use innerHTML.


#6

If you want to stick with something that creates the elements like createElement does, but want better performance, then you should look into using createDocumentFragment.

I like updating the innerHTML property, because it allows me to use template literals to make the code more readable, when there are multiple nested elements to add to the DOM.


#7

Pretty neat.

Is there a reason why you are not using the repeat function for your grid-template-columns?

grid-template-columns: repeat(14,1fr);

Also, I guess it doesn’t hurt to be explicit about it, but you don’t actually need the grid-template-rows property.


#8

I’ll checkout createDocumentFragment. But I agree with you. innerHTML is powerful. I think when it really comes down to it, I’d probably benefit by using less divs for each ghost and utilizing more CSS grid capabilities.

Anyways, I have some decisions to make.


#9

I always forget how powerful CSS is. Thanks for this.


#10

Hey! Great job, man! I like it.