{justCSS}

Just plain CSS

est. 2015

Fizz-buzz with just CSS

If you’ve ever been interviewed for a developer position, you have (no doubt) encountered the Fizz-buzz test. It’s a “simple” problem solving test used to quickly eliminate candidates who do not grasp the basics of programming.

My problem with this is that it has (somehow) made it’s way into front-end developer interviews where it is, apparently, OK to assume that you have to be a programmer to cope with the day-to-day tasks of writing JavaScript for front-end/UI/UX related tasks – I rate: bullshit! You will, almost certainly, never need to write programs with an advanced level of complexity and the Fizz-buzz test seems entirely unrelated to anything front-end.

Be that as it may, after some of my colleagues interviewed a candidate for a (Python) developer position recently and hearing them complain about the umpteenth person failing the Fizz-buzz test, I joked and said that I could probably do it with CSS … and I can … sort of. Let’s look at the test and see how close we get:

  1. Create a list of numbers from 1 – 100
  2. If the number is divisible by 3, print “Fizz”
  3. If the number is divisible by 5, print “Buzz”
  4. If the number is divisible by both, print “Fizzbuzz”
  5. Else, print the number

Create a list of numbers from 1 – 100

This is the only part that we cannot do with CSS, we’ll need to create an ordered list with 100 list items by hand :-/


<ol>
    <li></li>
    <li></li>
    
    <li></li>
    <li></li>
</ol>

We also set up some basic styling for our ordered list and list items – basically, we are going to use pseudo-elements to overlay the digits of our list items and then select which ones should print which term …

li{
  list-style: decimal inside;
  line-height: 1.5em;
  margin: 0;
  padding: 0;
  position: relative;
}
li::before{
  background: white;
  height: 1.5em;
  display: inline-block;
  position: absolute;
  left: 0;
}

If the number is divisible by n, print “Foo”

Easy enough, we use the :nth-child pseudo-class for this and create 3 selectors to match 3, 5 and 15 – we place the selector for 15 (Fizz-Buzz) last in our CSS, so that it overwrites the rules for 3 and 5; this is the opposite of how you would do it in a program …

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

Else, print the number

Nothing to do here, we’re already using an ordered (numbered) list *whoo-hoo* …

See the Pen gpPVeJ by Jacques Mostert (@jayx) on CodePen.14523

Notes on use:
This should just work in bloody well anything – so, next time you go for an interview and some clueless recruiter or HR person asks you Fizz-buzz, why not show off a little and do it with CSS only?

Comments?

Leave a Reply

Your email address will not be published. Required fields are marked *