<!DOCTYPE html>

<html>

<head>

<style>

  .container {

    display: flex;

    flex-wrap: wrap;

    width: 400px;

  }

  .box {

    width: 20px;

    height: 20px;

  }

  .red {

    background-color: red;

  }

  .black {

    background-color: black;

  }

</style>

</head>

<body>

 

<div class="container">

  <script>

    let colors = ['red', 'black'];

    let colorIndex = 0;

    let count = 20;

    let direction = 'right';

    let x = 0;

    let y = 0;

 

    while (count > 0) {

      for (let i = 0; i < count; i++) {

        let box = document.createElement('div');

        box.classList.add('box');

        box.classList.add(colors[colorIndex]);

        box.style.order = y * 20 + x;

        document.querySelector('.container').appendChild(box);

 

        if (direction === 'right') x++;

        if (direction === 'down') y++;

        if (direction === 'left') x--;

        if (direction === 'up') y--;

      }

 

      colorIndex = (colorIndex + 1) % colors.length;

 

      if (direction === 'right') direction = 'down';

      else if (direction === 'down') direction = 'left';

      else if (direction === 'left') direction = 'up';

      else if (direction === 'up') direction = 'right';

 

      if (direction === 'left' || direction === 'right

') count--;

    }

  </script>

</div>

 

</body>

</html>