Fizz Buzz in CSS

I was thinking about the classic programming problem Fizz Buzz recently. If you haven't come across Fizz Buzz before it's a simple game of mathematics. Players take turns counting incrementally, but if the number they are required to speak is divisible by three instead they say the word "Fizz". If the number is divisible by five, they say the word "Buzz". If it's divisible by both three and five "FizzBuzz" is said.

When programming Fizz Buzz is usually implemented as a simple loop, incrementing an integer and checking for divisibility by three and five, but I thought it might be interesting to look at alternative implementations.

To start with we are going to need some HTML structure to output our FizzBuzz results too. This is the only part that's not in CSS, but it doesn't really form part of the code, merely the substrate onto which we will output our results.

<ul>
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
    <li><div></div></li> 
</ul>

Now the CSS. First we clear the visuals on the list and create a counter.

ul {
    list-style-type: none;
    counter-reset: number;
}

Next we increment the counter at every list item.

ul li {
    counter-increment: number;
}

We set the content of each list item's inner div to contain the counter value. This takes care of the sequential counting.

ul li div:before {
    content: counter(number)
}

We then find all the items that are divisible by three or five and hide the inner divs so the number isn't shown.

ul li:nth-child(3n+3) div, ul li:nth-child(5n+5) div {
    display: none;
}

Finally we set the content of the list item to be either fizz or buzz. By using the before and after pseudo elements we can allow both to be set at the same time to form the FizzBuzz text when the value is divisible by both.

ul li:nth-child(3n+3):before {
    content: "Fizz";
}
ul li:nth-child(5n+5):after {
    content: "Buzz";
}

And there you go. Fizz Buzz implemented entirely in CSS.

Unless otherwise specified all code in this post is made available under the MIT license. Copyright 2013 Simon P Stevens.