CSS: word cloud

A word cloud is always something nice to do with CSS. All we need is a basic knowledge of CSS positioning and a couple of CSS transformations to add a final touch to our layout. Here's the background of this demo: I was searching the web for a PHP patch for Google Prettify and I simply stumbled on the following image:

Let's see how to get a similar result with CSS.

First it comes the markup:

<div id="word-cloud">

 <span class="word-1">css</span>
 <span class="word-2">xhtml</span>
 <span class="word-3">css</span>
 <span class="word-4">jquery</span>
 <span class="word-5">javascript</span>
 <span class="word-6">xml</span>
 <span class="word-7">html5</span>

</div>

Some of these words will be rotated by minus 90 degrees. Before digging into our example, we need to get a font similar to the one used in the image. We get the Yanone Kaffesatz Google font and we insert in our page like so:

<head>
<link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:regular,bold' rel='stylesheet' type='text/css' />
</head>

Before using any new web font, a good always is always this: check out the font metrics first or you might end up with specifying a too small or big font. Said that, here's our CSS code:

#word-cloud {
 width: 400px;
 height: 300px;
 margin: 0 auto;
 padding: 2em 0;
 font: 100% 'Yanone Kaffeesatz', Arial, sans-serif;
 position: relative;
}

#word-cloud span {
 position: absolute;
}

#word-cloud .word-1 {
 top: 1em;
 left: 1.5em;
 font-size: 100px;
 color: #626262;
}

#word-cloud .word-2 {
 top: 0;
 left: 1em;
 font-size: 80px;
 color: #906060;
}

#word-cloud .word-3 {
 top: 1em;
 left: 1.5em;
 font-size: 60px;
 color: #c5c5c5;
}

#word-cloud .word-4 {
 top: 1em;
 left: 0;
 font-size: 40px;
 color: #511c1c;
 -moz-transform: rotate(-90deg);
 -webkit-transform: rotate(-90deg);
 -o-transform: rotate(-90deg);
}

#word-cloud .word-5 {
 top: 1.5em;
 right: -0.3em;
 color: #666;
 font-size: 70px;
 -moz-transform: rotate(-90deg);
 -webkit-transform: rotate(-90deg);
 -o-transform: rotate(-90deg);
}

#word-cloud .word-6 {
 bottom: 0;
 right: 1em;
 color: #5e0000;
 font-size: 120px;
}

#word-cloud .word-7 {
 bottom: 0.6em;
 left: 0;
 color: #6e6e6e;
 font-size: 90px;
 -moz-transform: rotate(-90deg);
 -webkit-transform: rotate(-90deg);
 -o-transform: rotate(-90deg);
}

We've used only positioning and CSS transformations here. Bear in mind that when an element is positioned like so it's first turned into a block-level element and if we don't specify a dimension for it, its final dimensions will be calculated using the shrink-to-fit algorithm, that is, its width and height will be proportional to the amount of content contained within the element itself. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “CSS: word cloud”

Leave a Reply

Note: Only a member of this blog may post a comment.