Sometimes I post sourcecode accompanying my posts which are long and makes the length of the post unnecessarily long. The wordpress.com sourcecode shortcode has an option collapse which you can make “true” to collapse the sourcecode box when the page loads. If you post a long code, when the code box is expanded it will be inconvenient to scroll through the page and read. Also sometimes you might not want to collapse the codebox when the page loads. For this I have a solution. Add vertical bars to the codebox using the div tags.
In this way the length of the code portion in the page remains fixed and to read the code one requires just to scroll in the code box. Checkout what I am talking about in some of the code posts, for example in the posts here and here. Here is how it is done.

First open a div tag, and inside the div tag place your sourcecode block. Set the max-height css property of div tag to a pixel value to which you want to limit the height of the div block. Also set the css overflow property to auto or scroll to add the scrollbar. The overflow:auto; will add vertical scrollbar if the overflowed contented is clipped. The overflow:scroll; will add vertical scrollbar will be added. Using the max-height instead of the height attribute of div will let the length of the box grow to a maximum height of the specified pixel, and if the code length is shorter the box length will be as long as the code is. (Using height will make a fixed height box even if the code is shorter than the box length).

<div style="overflow:auto;max-height:800px;">
[ sourcecode language="cpp"]
Your source code goes here.
[ /sourcecode]
</div>

(Note: the blankspace between “[” and “sourcecode” and “/” in the above block is given, so that wordpress does not parse it as a shortcode.)

A mini example is shown below with a sample piece of code with 100px max height.

#include <stdio.h>

int main (int argc, char *argv[])
{
  printf ("Hello World!\n");

  return 0;
}

Generally I use 600px, 800px and 1000px to as the height of the div blocks. Also, instead of the sourcecode shortcode, one can use to limit a length of the content inside the pre tag or even in a paragraph. I hope this will be useful for some of those who want to post long code but still keep the page length short.

Some references:

Advertisement

One thought on “Add vertical scrollbar in wordpress.com sourcecode blocks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s