There are a couple of key mistakes in your example:
display: flex
affects an element's direct children - in this case, the element #tile
is acting as the child, and your .chessboard
elements are not affected.
For your colouring, the selector .chessboard div:nth-child(odd)
selects odd-child divs inside .chessboard
, not the chessboard elements themselves.
That said, I don't think either of these is what you want if you actually want to make a literal chess board, for a couple of reasons:
- A chess board is not a single array of squares, it's an 8x8 grid. Flexbox will wrap children wherever they fit, but you don't ever want 7 or 9 squares in a row.
- Continuous 'odd' numbering is not correct, you want odd numbers in even numbered rows, and even numbers in odd-numbered rows.
People have suggested using CSS grid, and that could work, however HTML has a built in 2D grid structure, the good old <table>
element! Example here: https://codepen.io/anon/pen/rgdNgq?editors=1111 (I've used Haml to simplify the HTML creation instead of javascript, but it's otherwise just 8 <tr>
with 8 <td>
's in each).
The key CSS is:
.chess-board {
border: 1px solid gray;
border-collapse: collapse;
border-spacing: 0;
}
.chess-board td {
padding: 0;
width: 4rem;
height: 4rem;
}
.chess-board tr:nth-child(odd) td:nth-child(even),
.chess-board tr:nth-child(even) td:nth-child(odd){
background: #222;
}
This is great for an actual chess-board because you can only ever have 8 x 8, guaranteed. CSS Grid can do it too, of course, but the main power of CSS grid is that the grid can change, which we don't want in this case.
The other good thing about a table structure is that you can address each row and column easily, because there's a structure grouping each row. With un-grouped cells, you need to always calculate a cell's number, which is easy enough, but just another step.