2020年12月21日星期一

Is there a way I can elegantly color my chess-piece squares with just CSS?

I have a grid-container with 64 grid-items. It's meant to represent a chess-board and it's arranged like so:

Never mind that the pieces are upside down - concentrate on the color of the squares and the grid-items - numbered in their appearance in source-order. enter image description here

The task is to color the squares like this picture. Here's some pseudo-code of how I achieved this with js:

let arrayOfSquares = Array.from(document.querySelectorAll(`.board-grid-container > div`));           for (let index = 0, total = 1; index <= 63; total++) {              arrayOfSquares[index].classList.add(`black-square`);              if (total === 4) {                  index = index + 3;              } else if (total === 8) {                  index = index + 1;                  total = 0;              } else {                  index = index + 2;              }          }  

My question is, could I have done this elegantly with CSS? The only way I could think of was to do something like this:

.board-grid-container > div:nth-child(n+2):nth-child(-n+8):nth-child(even) {      background-color: white;  }  .board-grid-container > div:nth-child(n+9):nth-child(-n+15):nth-child(odd) {      background-color: white;  }  .board-grid-container > div:nth-child(n+18):nth-child(-n+24):nth-child(even) {      background-color: white;  }  .board-grid-container > div:nth-child(n+25):nth-child(-n+31):nth-child(odd) {      background-color: white;  }  .board-grid-container > div:nth-child(n+34):nth-child(-n+40):nth-child(even) {      background-color: white;  }  .board-grid-container > div:nth-child(n+41):nth-child(-n+47):nth-child(odd) {      background-color: white;  }  .board-grid-container > div:nth-child(n+50):nth-child(-n+56):nth-child(even) {      background-color: white;  }  .board-grid-container > div:nth-child(n+57):nth-child(-n+63):nth-child(odd) {      background-color: white;  }  
https://stackoverflow.com/questions/65401997/is-there-a-way-i-can-elegantly-color-my-chess-piece-squares-with-just-css December 22, 2020 at 09:04AM

没有评论:

发表评论