Intro

I have seen demos of pure CSS Tic-tac-toe games, but I was unable to find a version that truly works. If I have missed it, please send me link, so I can see how another dev has created it.

My version works as any normal Tic-tac-toe game would: 2 players can play against each other, it can result in either a win or a tie. Players can also restart the game.

In my CodePen example, I used Jade and SASS, so that my code looks much cleaner and simpler to understand.

Demo

How it works:

  • It uses hidden radio buttons for the states, and labels for the visible part.
  • There are 9 possible turns, in each turn a player can only click on one label.
  • Once the user clicks on a label, it changes the radio button state to :checked
  • When the :checked state is triggered, the CSS moves to the next turn by using z-index:

    • z-index: 1 for turn one,
    • z-index: 2 for turn two,
    • etc.

    It also pushes the clicked label on top (z-index: 10)

  • Player 1 plays on odd turns and player 2 plays on even turns. Each label has a class .turn-x added to it, so we know which turn it is assigned to.
  • To determine which player won, we check for all posibble victories, for both players individually. In HTML we have classes added, so each label is a part of a column, row or diagonal. Example for player 1, first column victory:

    .player-1.first-column:checked ~ .player-1.first-column:checked ~ .player-1.first-column:checked ~ .end

  • To restart the game, I used a normal <a> tag, but left the href attribute empty, so it forces a refresh.

The game should work on any browser that supports CSS3 selectors.

Conclusion

This is my first game that uses only HTML and CSS. I already have a couple of ideas for creating some more Pure CSS games, so keep an eye out. I really enjoyed using a simple method, that we use everyday day, to create a fully functional game.

Hopefully this post will inspire you to explore CSS and create your own game. :)


6,749 3 56