1. Home
  2. Computing & Technology
  3. JavaScript

Drawing with Stylesheets and Javascript

3. HTML

clr gif

In looking at how we can build picture components from stylesheets let's start by looking at the code required to "draw" one of the black keys onto the page. Here's the code:

<div class="bl"></div>

That code will place a black rectangle exactly 11 pixels by 60 pixels at the left of the page immediately to the right of anything that has already been floated left.

Of course for our keyboard there is a white key immediately to the left of the first black key so we would need to define that key before the black one we just looked at. Unlike the black key we don't have a single class that defines what we need for that white key but that is okay because we can just reference all of the classes that we need like this:

<div class="wt w14 l"></div>

So this white key is constructed from three classes (wt, w14, and l). The rest of the individual components are created the same way.

Simply by coding divs like this for the 36 keys in the top part of our keyboard one after the other in the right order we can construct the top half or the drawing. Note that the float:left in one of the classes attached to each div ensures that it will go on the same line immediately to the right of the previous div rather than starting a new line the way that divs normally do. We have to use divs rather than spans because you can't assign a height to a span.

The second row is constructed exactly the same as the first row by placing the divs one next to the other. Of course we don't want the first div for the second row to go next to the last div on the first row so we group all of the divs for one row together by placing them within another div like this:

<div class="clear">
<!-- divs for one row of the drawing go here -->
</div>

If you just want a static drawing that will display in any browser that supports stylesheets then that is all that you need to do to create your drawing. Provided that you don't need the drawing to show in browsers that don't have Javascript enabled we can use Javascript to code the drawing and greatly reduce what we need to write.

Explore JavaScript
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.