The Game of Life with CSS3 Flexible Boxes and React

Published on by Morgan Ney

The game of life is an example of cellular automaton and a popular programming assignment for computer science students. I wanted to put together a basic implementation of the algorithm using CSS3 Flexbox and React. Below is a gist of a React component encapsulating the game logic and a demonstration of a running example.

Thanks to CSS3 Flexbox (and browsers that support it) positioning and sizing the cells in the grid across a spectrum of user agents and viewport sizes is easy. Once you define an element to be a flex container using the flex value of the display property, i.e. display: flex; all child elements become flexible boxes, including text. All that is left to do is specify how these flex box children should orient themselves inside the container and adapt to available display space.

First, here is the HTML for a 2x2 game grid. The classes are for coloring the live from the dead cells, and sizing the cells based on the selected grid size so that flex-wrap: wrap; breaks the "rows" at the correct cell.

Here is the associated CSS for styling the flex container <section> and the flex items <span>. The CSS units for viewport-percentage lengths vw, vh, and vm can help keep the flex container square. In this case I just used vw.

Finally, a CSS preprocessor can help generate the styles needed to properly size the <span> flex items for different grid sizes. Since I already use node I generate the styles in less to avoid the extra sass dependency on ruby.

Of course the bounds on the grid size are arbitrary and only limited by available time and space. Maybe next time I'll explore creating the cell grid with the Canvas API. The source code for the game of life just demonstrated is hosted on github.

Relevant to  CSS3 Flexible Box, Less, React
Get in Touch

BizzyBtyes is owned by Morgan Ney, a father, husband, and web developer originally from the San Francisco Bay Area and now living in Coarsegold, Ca. just south of Yosemite.