Sliding Puzzle

The aim of this challenge is to use HTML, CSS and Javascript to create an interactive sliding puzzle.

Step 1: Creating 9 tiles from a single picture, using CSS

Our aim is the use a single picture file called flower.png and to create 9 CSS classes for each tile of the picture as displayed below:

We will create our tiles using DIV tags. We will use the flower.png picture file as the background for each tile and by applying different background-position we will create the 9 different tiles as needed.

Step 2: Table Layout

We now need to position our 9 tiles using a 3×3 table layout in HTML & CSS. To do so, we will use the display property in CSS using the following three options:

  • display: table;
  • display: table-row;
  • display: table-cell;

This is an alternative to using the <TABLE>, <TR> and <TD> tags in HTML.

Step 3: Adding Interactivity and Game Logic using JavaScript

For each cell we will add an onClick attribute to call a JavaScript function to implement the game logic when the user clicks on one of the 9 cells.

We will also add a re-shuffle button to shuffle all the tiles and start a new game.

Full Code

We have implemented the HTML and CSS code above and added on onClick attribute on each tile. When a tile is clicked the javascript function clickTile() is called. This is where the code will check if the tiles can be swapped.

We have also added the “New Game” button and the JavaScript code to reshuffle all the tiles of the grid.

See the Pen Sliding Puzzle by 101 Computing (@101Computing) on CodePen.

Note that this script uses one picture. In case this picture is not displaying properly, you may have to replace its URL in the CSS code, using the following address:

Your Challenge

Amend the HTML, CSS and JavaScript code provided above to create a sliding puzzle based on a 4×4 grid (instead of 3×3).


  1. Start by changing the HTML code to add enough <DIV> tags to create a grid of 16 tiles.
  2. Change the CSS code to add extra classes for .tile10, .tile11, … to .tile16.
    Not that you will have to use more accurate background positioning using the following approach:

    You will also need to revisit the CSS definitions for classes .tile1, .tile2, … to .tile9.
    Note that the white tile should now be tile 16.

  3. Adapt the JavaScript code to ensure it works with a 4 by 4 grid instead of a 3 by 3 grid.


The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 4.6 / 5. Vote count: 5

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: