If you’ve been frequenting programming-themed blogs, you may have noticed expanding code blocks. They’re code blocks that expand when you hover over them, so that text will wrap at a further line and you can read it more easily.

Until today, my blog didn’t have those, and I felt very, very disadvantaged. Why must my code wrap while the other kids’ code is nice and straight? Was I less cool?

Well, no longer. Today I have implemented this expansion, and it only took a few minutes. I Googled around for solutions, but all the proposed ones seemed to be jQuery-based, and I didn’t want to use Javascript for this, since that seemed overly complicated. I recalled that CSS3 includes some transition attributes, so I read up on them, and they are very easy to use.

The method

The easy-and-ugly method is to just set width to whatever you like (I used 150%) on :hover. This expands the element that contains the code listing when the user hovers over it, and contracts back to normal size when the mouse moves off it.

Unfortunately, the expansion is done instantly, so it is a bit jarring. This is where the CSS3 transition comes in. Just specify the following attributes:

transition: width .5s ease;
-webkit-transition: width .5s ease;

This means that any change to the element’s width will be done smoothly over 0.5 seconds, with easing. There was a small bug in my CSS that started the resizing from 0, rather than 100% of the width, but this was easily fixed by setting the initial width to 100% rather than leave it undefined.

That’s pretty much it! Here’s the result:

metasyntactic_variables = [metasyntactic_variable.name for metasyntactic_variable in stuff if metasyntactic_variable.name == "foo"]

Obviously, hover over it to see the expansion. Pretty simple, and no JS needed!