Piano in CSS and HTML

When I first started working on the Digitizing Bach app, my first task was to create a Piano menu.

It's been a while, but I remember this being tricky to get down. Especially as, at the time, I was just beginning to learn about HTML and CSS.

Eventually I got it though, and later updated my code for a more adaptive design (something that scales to whatever size you want). I thought I'd share my solution if anybody ever looks for the same thing I was looking for.

Here it is in action!

I have this Piano Menu documented on the GitHub Wiki page, but here are the basics:

The Rundown

It uses div elements. The main shell acts as a table and the immediate children div elements become cells. This way, each key's width will scale to evenly fill the entirety of the table.

White keys are easy and are styled using the class "key".

Black keys were a bit trickier. If you put them in directly, they would space out the white keys. Instead, I have div element with the class "innerKey" wherever a black key should be. These are hard-set a width of 0px, and sit on top of the white "key" class.

Within this innerKey are the black keys, with a div element given the class "blackKey". They are given a shorter height, absolute positioning, and a small % width (so that as the tables width grows, they scale accordingly.

At this stage your black keys should be in position, but to the right. Simply add a margin-left of 1/2 the width of the black key and they should always center where they're supposed to be!

With this setup, you can easily add hover effects and assign separate click functions for each individual key. As long as each key itself has it's own identifying class or ID, then you can point to it in jQuery.

Happy coding!